########### Python Form Recognizer Async Analyze #############
import json
import time
from requests import get, post


# Endpoint URL
def test_invoices(source, labels):
    endpoint = r"https://form-recog1.cognitiveservices.azure.com/"
    apim_key = "9747a2a5ce2f426793b3c05bc2b34c17"
    # model_id = "c2c1a822-7083-455a-879d-c53aa9ff00c5"
    model_id = labels['modelId']
    print(model_id)
    post_url = endpoint + "/formrecognizer/v2.0-preview/custom/models/%s/analyze" % model_id
    print(source)
    # source = r"Test/Invoice_6.pdf"
    params = {
        "includeTextDetails": True
    }

    headers = {
        # Request headers
        'Content-Type': 'application/pdf',
        'Ocp-Apim-Subscription-Key': apim_key,
    }
    with open(source['path'], "rb") as f:
        data_bytes = f.read()

    try:
        resp = post(url=post_url, data=data_bytes, headers=headers, params=params)
        if resp.status_code != 202:
            print("POST analyze failed:\n%s" % json.dumps(resp.json()))
            quit()
        print("POST analyze succeeded:\n%s" % resp.headers)
        get_url = resp.headers["operation-location"]
    except Exception as e:
        print("POST analyze failed:\n%s" % str(e))
        quit()

    n_tries = 15
    n_try = 0
    wait_sec = 5
    max_wait_sec = 60
    while n_try < n_tries:
        try:
            resp = get(url=get_url, headers={"Ocp-Apim-Subscription-Key": apim_key})
            resp_json = resp.json()
            if resp.status_code != 200:
                print("GET analyze results failed:\n%s" % json.dumps(resp_json))
                return "Failed"
            status = resp_json["status"]
            if status == "succeeded":
                # print(resp_json)
                # print(
                #     "Analysis succeeded:\n%s" % json.dumps(resp_json))
                Result = {}
                num = resp_json['analyzeResult']['documentResults'][0]["fields"][labels['trainedLabels'][0]]["valueString"]
                dt = resp_json['analyzeResult']['documentResults'][0]["fields"][labels['trainedLabels'][1]]["valueString"]
                for i in labels['trainedLabels']:
                    Result[i] = resp_json['analyzeResult']['documentResults'][0]["fields"][i]["valueString"]
                print(Result)
                # print("Analysis succeeded:\n%s" % json.dumps(
                #     resp_json['analyzeResult']['documentResults'][0]["fields"]["Invoice Number"]["valueString"]))
                # print("Analysis succeeded:\n%s" % json.dumps(
                #     resp_json['analyzeResult']['documentResults'][0]["fields"]["Invoice Due Date"]["valueString"]))
                # quit()
                return Result
            if status == "failed":
                print("Analysis failed:\n%s" % json.dumps(resp_json))
                return "Failed"
                # quit()
            # Analysis still running. Wait and retry.
            time.sleep(wait_sec)
            n_try += 1
            wait_sec = min(2 * wait_sec, max_wait_sec)
        except Exception as e:
            msg = "GET analyze results failed:\n%s" % str(e)
            print(msg)
            return "Failed"
    print("Analyze operation did not complete within the allocated time.")
