from win32com.universal import com_error
from win32com.client import DispatchEx
import pythoncom
import json
import base64
import sys

sys.path.insert(0, './libs.zip')


def prepare_for_oicf(q, data, convert_base64):
    result = {}
    result["status"] = 200

    # checking if request is PDA error information
    if data["PdaError"] and not data["json"]:
        result["response"] = "{\"error_state\": \"OK\", \"error_message\": \"OK\", \"error_text\": \"OK\"}"
        result["status"] = 200
        q.put(result)
        return

    if convert_base64 in ["D", "d"] and data["json"]:
        b64_data = base64.b64encode(data["json"].encode())
        data["json"] = "base64"+b64_data.decode("utf8")

    result_data, result_status = execute_oicf(data)

    if data["deserialize"] and result_status["error"] == False:
        result_data = json.loads(result_data)
        result_data = json.loads(result_data["data"])
        result_data = str(result_data["databaseattachment"])

    result["response"] = result_data
    result["error_message"] = result_status.get("error_message", "")
    result["error"] = result_status.get("error", False)
    result["status"] = result_status.get("status", 200)
    q.put(result)


def execute_oicf(data):
    return_result = ""
    return_status = {}
    _oicf = None
    try:
        pythoncom.CoInitialize()
        if data["OicfType"] == "S":
            _oicf = DispatchEx("OICF.TOICF")
        elif data["OicfType"] == "E":
            _oicf = DispatchEx("OICFE.TOICFE")
        else:
            _oicf = DispatchEx("OICF.TOICF")

        if data["NewApi"] in ["N", "n"]:
            return_result = _oicf.Execute(data["json"],
                                          int(data["DebugLevel"]),
                                          data["DebugSection"],
                                          data["DebugParams"],
                                          data["InfoAPIPath"])
        else:
            return_result = _oicf.Execute2018(data["json"],
                                              int(data["DebugLevel"]),
                                              data["DebugSection"],
                                              data["DebugParams"],
                                              data["APIVersion"])
            if type(return_result) == tuple:
                return_result = return_result[0]
            return_status["status"] = 200
    except com_error as err:
        return_status["status"] = 200
        return_result = "{\"error_state\": \"oicf_interface_error\", \"error_message\": \"" + err.strerror + "\", \"error_text\": \"apiAPI: " \
            + str(err.excepinfo) + "\"}"
        return_status["error"] = True
        return_status["error_message"] = f"ERROR: {err.args[1]} \nREQUEST: {data['json']} \nRESPONSE: {return_result}"
    finally:
        # ciscenje objekta
        _oicf = None
        del _oicf
        # oslobadjanje memorije
        pythoncom.CoUninitialize()
        pythoncom.CoFreeUnusedLibraries()

    return return_result, return_status
