##
#  Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
#
#  File :      test_sync.py
#
#  Purpose :   Demonstrates how to submit an optimization problem
#              to the MOSEK OptServer and solve it in synchronous mode.
##

import requests, sys, argparse, json

if __name__ == '__main__':
    # Arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("--url", help="URL of the remote server", type=str, required=True)
    parser.add_argument("--infile", help="Input file to optimize", type=str, required=True)
    parser.add_argument("--intype", help="Content type of the input, for example application/x-mosek-mps", type=str, required=True)
    parser.add_argument("--outtype", help="Content type of the response, for example application/x-mosek-json", type=str, required=True)
    args = parser.parse_args()
    URL = args.url
    infile = args.infile
    intype = args.intype
    outtype = args.outtype
    verify = False # Whether to verify SSL certificates

    # Create a connection
    with requests.Session() as s:
        with open(infile,'rb') as probdata:
            # POST problem data
            submit = s.post(URL + "/api/v1/submit", 
                            data = probdata,
                            headers = { "Content-Type" : intype },
                            verify = verify )

            if submit.status_code == 200:
                token = submit.headers['X-Mosek-Job-Token']
                print("Submit: success")

                # Request the server to solve the problem
                solve = s.get(URL + "/api/v1/solve", 
                              headers = { "X-Mosek-Job-Token" : token,
                                          "Accept": outtype },
                              verify = verify )

                if solve.status_code == 200:
                    if outtype in ["application/json", "application/x-mosek-jtask"]:
                        solution = json.loads(solve.text)
                    else:
                        solution = solve.text
                    res = solve.headers["X-Mosek-Res-Code"]
                    trm = solve.headers["X-Mosek-Trm-Code"]

                    # Obtain the solver log output
                    log = s.get(URL + "/api/v1/log",
                                headers = { "X-Mosek-Job-Token" : token },
                                verify = verify )
                    print(log.text)

                    print(f"Solution: {solution}")
                    print(f"Response code:    {res}")
                    print(f"Termination code: {trm}")
                else:
                    print(f"Error solving the problem, status = {solve.status_code}")
            else:
                print(f"Unexpected status {submit.status_code}")
                print(f"Response: {submit.text}")
                print(f"Headers:  {submit.headers}")
