##
#  Copyright : Copyright (c) MOSEK ApS, Denmark. All rights reserved.
#
#  File :      test_simple_api.py
#
#  Purpose :   Demonstrates how to use the simple submit+solve API
##

import http.client
import sys
try:
    import ssl
except:
    pass

# A debug method which prints out the HTTP(S) response 
# and exits in case of error
def check_status(resp):
    print('\tHTTPResponse: %s / %s' % (resp.status,resp.reason))
    for k,v in  resp.getheaders():
        print('\t%s: %s' % (k,v))
            
    if resp.status not in [http.client.OK, http.client.NO_CONTENT]:
        raise Exception('An error in connection')

# A helper method which opens a connection
def openConnection(host, port, useHttps):
    if useHttps:
        return http.client.HTTPSConnection(host, port, context=ssl._create_unverified_context())
    else:
        return http.client.HTTPConnection(host, port)

# Main code
if __name__ == '__main__':
    try:
        # OptServer address
        host, port = sys.argv[1], int(sys.argv[2])
        # Protocol (HTTP/HTTPS)
        useHttps = (sys.argv[3] == "HTTPS")
        # Name of file with input data
        probfile = sys.argv[4]        
        # Input and output file type
        intype, outtype = sys.argv[5], sys.argv[6]
        # Jobname (for demonstration)
        jobname = sys.argv[7] 
        # Authentication token
        headers = {}
        if len(sys.argv) == 9:
            headers = {"X-Mosek-Access-Token": sys.argv[8]}
    except:
        print("Usage  : python3 test_simple_api.py host            port  protocol  probfile intype outtype    jobname     [accestoken]")
        print("Example: python3 test_simple_api.py solve.mosek.com 38000 HTTPS     lo1.mps  mps    text/plain SimpleTask  ...")
        sys.exit(1)

    # Establish HTTP connection
    con = openConnection(host, port, useHttps)
    try:
        # Read input file
        with open(probfile,'rb') as probdata:
            ## Submit job
            print('POST /api/submit+solve')
            # POST problem data
            con.request('POST', '/api/submit+solve?jobname=' + jobname, 
                                probdata, 
                                headers = dict(headers, **{"Content-Type": "application/x-mosek-{}".format(intype),
                                                           "Accept": outtype}))
            resp = con.getresponse()
            check_status(resp)
            # Recover a token identifying the job
            token = resp.getheader('X-Mosek-Token',None) 

            ## Retrieve status codes
            res = resp.getheader('X-Mosek-Res-Code',None) 
            trm = resp.getheader('X-Mosek-Trm-Code',None) 
            print('\tMOSEK response: %s' % res)
            print('\t      trm resp: %s' % trm)

            ## Retrieve the solution
            if resp.status == http.client.OK:
                print('Solution (as plain text):\n')
                print(resp.read().decode('ascii', errors = 'ignore'))

            ## Obtain the solver log output
            print('GET /api/log')
            con.request('GET','/api/log?token=' + token, headers = headers)
            resp = con.getresponse()
            check_status(resp)
            if resp.status == http.client.OK:
                print('Solver log:\n')                
                print(resp.read().decode('utf-8', errors = 'ignore'))
    finally:
        con.close()
