# *********************************
# Structural functions for dmaatti.py
# Contains structural functions to keep the main file cleaner
# Matti Sarkela 1.2.2019
# *********************************
from pa_Dmaatti import *

initOKtext = "Initializing OK - Payments allowed!"

def checkRegisterPos(response):
    if (response.status_code == 400):
        # PoS IS is not registered, write to log and try to register (no need to run UnRegisterPoS).
        print("No PoSID registered, try to register PoS ID and PoS Unit Id")
        writeLog("ReadPoSAssignPoSUnitId: PoS Unit ID not Assigned! Try to register PoS and assign PoS Unit ID. ", "WARNING", response)
        response = apiRequest("RegisterPoS", RegisterPoS)
        if (response.status_code == 400):
            print("RegisterPoS: FATAL - PoS register failed!")
            writeLog("RegisterPoS: Could not register PoS. Exit program.", "FATAL", response)
            sys.exit("FATAL ERROR - PoS register failed!")
        elif (response.status_code == 200):
            #PoS registered, try to assign Unit ID to PoS
            print("PoS ID is now registered - OK")
            writeLog("RegisterPoS: PoS registered.", "OK", response)
            tryAssignUnitId()
        else:
            print("Unexpected error with RegisterPoS.")
            writeLog("RegisterPoS: Unexpected error. Exit program.", "FATAL", response)
            sys.exit("UNEXPECTED FATAL ERROR - PoS register failed!")

    elif (response.status_code == 200):
        # PoS ID is registered. Check that received data corresponds to our memory.
        # If PoS is registered, but PoS Unit ID is not assigned, there will be empty
        # string and we must just assign PoS Unit ID.
        print("PoSID is registered")
        #This is the branch we want be in.
        if (json.loads(response.text)['PoSUnitId'] == PoSUnitId):#+"1"):
            print("PoSID matches expected - OK")
            print(initOKtext)
            writeLog("ReadPoSAssignPoSUnitId: PoS Unit ID is registered and matches to expected.", "OK", response)
            writeLog(initOKtext, "OK")
            writeLog(logSeparator2)
        
        elif (json.loads(response.text)['PoSUnitId'] == ""):
            print("... but PoSUnitId is empty. - Try to assign.")
            writeLog("PosID is registered, but PoSUnitId is empty, try to assign it.", "INFO")
            tryAssignUnitId()
        else:
            #If PoS ID is corrupted assign again
            print("PoSID is not expected and not empty. - Try to assign again.")
            response = apiRequest("UnAssignPoSUnitIdToPoS", UnAssignPoSUnitIdToPoS)
            if (response.status_code == 400):
                print("UnAssignPoSUnitIdToPoS gave error, try to clean with UnRegisterPoS and exit")
                writeLog("UnAssignPoSUnitIdToPoS: Could not unassing old PoS unit.", "FATAL", response)
                response = apiRequest("UnRegisterPoS", UnRegisterPoS)
                writeLog("UnRegisterPoS: Try to clean after error.", "INFO", response)
                sys.exit("FATAL ERROR: UnAssignPoSUnitIdToPoS - Could not unassing old PoS unit. Exit program.")
            elif (response.status_code == 200):
                #If unassignment was succesful, assign new Pos ID (from memory, this should have been also in MobilePay backend
                print("UnAssignPoSUnitIdToPoS was successfull.")
                writeLog("UnAssignPoSUnitIdToPoS: Unassignment succesfull.", "OK", response)
                response = apiRequest("AssignPoSUnitIdToPos", AssignPoSUnitIdToPos)
                if (response.status_code == 400):
                    writeLog("AssignPoSUnitIdToPos: Could not assign new PoS unit ID.", "FATAL", response)
                    sys.exit("FATAL ERROR: AssignPoSUnitIdToPos - Could not assing new PoS unit ID. Exit program.")
                elif (response.status_code == 200):
                    #Start up was recovered, but there was an error with PoSUnitId. Check what is going on if this continues.
                    print("AssignPoSUnitIdToPos was successfull.")
                    print(initOKtext)
                    writeLog("AssignPoSUnitIdToPos: Assignment was succesfull.", "OK", response)
                    writeLog("Dmaatti PoSUnitId was not expected at the beginning. If there some persistent problem?", "WARNING")
                    writeLog(initOKtext, "OK")
                    writeLog(logSeparator2)
                else:
                    writeLog("AssignPoSUnitIdToPos: Unexpected error. Exit program.", "FATAL", response)
                    sys.exit("UNEXPECTED FATAL ERROR - Assignent of PoS Unit ID failed!")
            else:
                print("Unexpected error with UnAssignPoSUnitIdToPoS.")
                writeLog("UnAssignPoSUnitIdToPoS: Unexpected error. Exit program.", "FATAL", response)
                sys.exit("UNEXPECTED FATAL ERROR - Unassignent of PoS Unit ID failed!")
    else:
        print("Unexpected error with ReadPoSAssignPoSUnitId.")
        writeLog("ReadPoSAssignPoSUnitId: Unexpected error. Exit program.", "FATAL", response)
        sys.exit("UNEXPECTED FATAL ERROR - PoS register failed to query state!")
        
def tryAssignUnitId():
    response = apiRequest("AssignPoSUnitIdToPos", AssignPoSUnitIdToPos)
    if (response.status_code == 400):
        print("AssignPoSUnitIdToPos: FATAL - PoS Unit ID register failed!")
        writeLog("AssignPoSUnitIdToPos: Could not register PoS Unit ID. Exit program.", "FATAL", response)
        response = apiRequest("UnRegisterPoS", UnRegisterPoS)
        writeLog("UnRegisterPoS: Tried to unregister after fatal error.", "INFO", response)
        sys.exit("FATAL ERROR - PoS Unit ID register failed!")
    elif (response.status_code == 200):
        # Register successfull. But there is maybe something going on while Dmaatti should be always registered to MobilePay backend with unique credentials.
        print("PoS Unit ID is registered - OK")
        print(initOKtext)
        writeLog("AssignPoSUnitIdToPos: PoS Unit ID is registered.", "OK", response)
        writeLog("Dmaatti was dropped from MobilePay backend.", "WARNING")
        writeLog(initOKtext, "OK")
        writeLog(logSeparator2)

def getAndLogPaymentStatus(previousStatus = 0):
    response = apiRequest("GetPaymentStatus", GetPaymentStatus)
    status = json.loads(response.text)['PaymentStatus']
    
    if (status != previousStatus):
        if (status == 20):
            writeLog("Payment status changed to 20 - Payment issued", "INFO", response)
        elif (status == 30):
            writeLog("Payment status changed to 30 - Waiting customer chekc-in to store", "INFO", response)
        elif (status == 40):
            writeLog("Payment status changed to 40 - Customer rejected payment", "INFO", response)
        elif (status == 50):
            writeLog("Payment status changed to 50 - Error, MobilePay can't continue with payment", "INFO", response)
        elif (status == 60):
            writeLog("Payment status changed to 60 - Payment recalculation needed", "INFO", response)
        elif (status == 80):
            writeLog("Payment status changed to 80 - Payment accepteed", "INFO", response)
        elif (status == 100):
            writeLog("Payment status changed to 100 - Done", "INFO", response)
        else:
            writeLog("Payment status changed to unrecognized: " +str(status), "ERROR", response)
    
    return status
    
def cancelLastPayment():
    response = apiRequest("PaymentCancel", PaymentCancel)
    if (response.status_code == 400):
        writeLog("PaymentCancel: Tried to cancel payment.", "FATAL", response)
        sys.exit("FATAL ERROR - PaymentCancel did not succeed.")
    else:
         print("Payment cancel OK")
         
def unAssignments():
    # input("Press Enter to continue UnAssignPoSUnitIdToPoS")
    apiRequest("UnAssignPoSUnitIdToPoS", UnAssignPoSUnitIdToPoS)
    # print(" ")
    # input("Press Enter to continue UnRegisterPoS")
    apiRequest("UnRegisterPoS", UnRegisterPoS)
    # print(" ")