# *********************************
# Dmaatti Main program.
# Waits inputs and handles payments.
# Matti Sarkela 1.2.2019
# *********************************

from pa_Dmaatti import * #Or import stuff one by one: from pa_Dmaatti import ApiKey  / import apiRequest
from dmaattiFuncs import *

timeOutLimit = 20 #Seconds to wait timeout in PaymentStart
orderValue = "0"


# varasto = {
# "22":"10", 
# "50":"1", 
# "88":"0",
# "99":"5" 
# }

# hinnat = {
# "22":"0.50",
# "50":"0.99",
# "88":"1.50",
# "98":"1.00"
# }

print("START")
writeLog(" ********** START OF DMAATTI.PY **********")

# print(RegisterPoS)
# updateUniquePoSId("moooo")
# print(RegisterPoS)

# method = "GetUniquePoSId"
# apiRequest(method, GetUniquePoSId)

# input("Press Enter to continue RegisterPoS")
# apiRequest("RegisterPoS", RegisterPoS)
# print(" ")
# input("Press Enter to continue AssignPoSUnitIdToPos")
# apiRequest("AssignPoSUnitIdToPos", AssignPoSUnitIdToPos)
# apiRequest("ReadPoSAssignPoSUnitId", ReadPoSAssignPoSUnitId)
# apiRequest("ReadPoSUnitAssignedPoSId", ReadPoSUnitAssignedPoSId)
# print(" ")

# input("Press Enter to continue GetCurrentPayment")
# print(GetCurrentPayment)
# apiRequest("GetCurrentPayment", GetCurrentPayment)

# **** TEST PROGRAM *************

# Dmaatti should always be registered in MobilePay backend, even though machine itself is shutdown.
# Read PoSUnitId assigned to current PoS terminal to determine if RegisterPoS is valid.
response = apiRequest("ReadPoSAssignPoSUnitId", ReadPoSAssignPoSUnitId)
checkRegisterPos(response)
cancelLastPayment() #If system was shutdown, there may have been unfinished payments
inventory = readInventory()


# input("Press Enter to continue GetPosList") 
# apiRequest("GetPosList", GetPosList)
# print(" ")

# input("Press Enter to continue GetPaymentStatus") 
# apiRequest("GetPaymentStatus", GetPaymentStatus)
# print(" ")

# input("Press Enter to continue GetPaymentStatus") 
# apiRequest("GetPaymentStatus", GetPaymentStatus)
# print(" ")

# input("Press Enter to continue ReadPoSAssignPoSUnitId")
# apiRequest("ReadPoSAssignPoSUnitId", ReadPoSAssignPoSUnitId)
# input("Press Enter to continue ReadPoSUnitAssignedPoSId")
# apiRequest("ReadPoSUnitAssignedPoSId", ReadPoSUnitAssignedPoSId)

# ------------------------------
# We are ready to take payments! Stay in loop as  long as secret code is set
while (orderValue != "999"):
    orderValue = input("Anna tuotteen numero: ")
    timeoutCnt = 0
    if (inventory.get(orderValue) != None and inventory[orderValue]["stock"] != "0"):
        print("Varastossa: " + str(inventory[orderValue]["stock"]))
        print("Hinta: " +  str(inventory[orderValue]["price"]))
        # print("Varastossa: " + str(inventory.get(orderValue)))
        # print("Hinta: " + str(inventory.get(orderValue)))
        
        # input("Press Enter to continue PaymentStart")
        #Create PaymentStart request if there is item
        OrderId = "TESTI"+datetime.now().strftime("%y%m%d%H%M%S")  #This is running number, created from current time. Max length 18
        PaymentStart["OrderId"] = OrderId
        PaymentStart["Amount"] = str(inventory[orderValue]["price"])
        paymentStartHMAC()
        GetPaymentStatus["OrderId"] = OrderId #Update payment status
        
        response = apiRequest("PaymentStart", PaymentStart) # What is ReCalc? Do we need to care that in response?
        if (response.status_code == 200):
            paymentStatus = getAndLogPaymentStatus()
            while(paymentStatus != 40 and paymentStatus != 50 and paymentStatus != 60 and paymentStatus != 100 and timeoutCnt <= timeOutLimit):
                time.sleep(1) #Wait 1s, this is the fastest limit polling can be done
                paymentStatus = getAndLogPaymentStatus(paymentStatus)
                timeoutCnt = timeoutCnt + 1
                # print(timeoutCnt)
                # Counter to Dmaatti display??
            
            #Tulosta näyttöön info tapahtumneesta aina eri tapauksissa
            if (timeoutCnt >= timeOutLimit):
                print("Timeout in payment! Cancel payment.")
                writeLog("Timeout occurred. Took more than "+str(timeOutLimit)+"s to make payment","ERROR")
                cancelLastPayment()
            elif (paymentStatus == 40):
                # paymentStatus = getAndLogPaymentStatus(paymentStatus)
                print("Customer canceled payment.")
                writeLog("Customer canceled payment.","INFO")
            elif (paymentStatus == 50):
                # paymentStatus = getAndLogPaymentStatus(paymentStatus)
                print("MobilePay can't process payment.")
                writeLog("MobilePay can't process payment.","ERROR")
                cancelLastPayment()
            elif (paymentStatus == 60):
                # paymentStatus = getAndLogPaymentStatus(paymentStatus)
                print("Recalculation needed.")
                writeLog("Recalculation needed, we don't support that!","ERROR")
                cancelLastPayment()
            elif (paymentStatus == 100):
                # paymentStatus = getAndLogPaymentStatus(paymentStatus)
                print("Payment confirmed!")
                writeLog("Payment confirmed!","OK")
                inventory[orderValue]["stock"] = str(int(inventory[orderValue]["stock"])-1)
                writeInventory(inventory)
            else:
                print("Unexpected error.")
                writeLog("Weird problem, should never be here.","ERROR")
                cancelLastPayment()
            
            #Divide all orders with separator in log
            writeLog(logSeparator)

        else:
            print("NOT IMPLEMENTED YET") #What to do is response for payment start is 400?
        
        # input("Press Enter to continue GetPaymentStatus") 
        # apiRequest("GetPaymentStatus", GetPaymentStatus)
        # print(" ")
    # elif (inventory.get(orderValue) != None ):
        # print("Does not exist in the machine. Tried to order: " +orderValue)
        # writeLog("Does not exist in the machine. Tried to order: " +orderValue,"ERROR")
        
    # elif (inventory[orderValue]["stock"] == "0"):
        # print("Inventory says spiral is empty! Tried to order: " +orderValue)
        # writeLog("Inventory says spiral is empty! Tried to order: " +orderValue,"ERROR")
    
    elif (inventory.get(orderValue) != None and inventory[orderValue]["stock"] == "0"):
        print("Varastotilanne 0!")
        writeLog("No requested items in stock!!","ERROR")
        
    elif (orderValue == "000"):
        writeInventory(inventory)
        
    elif (orderValue == "001"):
        inventory = readInventory()
        print(inventory)
        
    elif (orderValue == "333"):
        print("333 ei oleee")

    
    else:
        print("Ei ole inventoryssa numerolla: " +str(orderValue))

        
writeLog(" ********** CLOSE DMAATTI.PY **********")    



# input("Press Enter to continue GetPaymentStatus") 
# apiRequest("GetPaymentStatus", GetPaymentStatus)
# print(" ")

# input("Press Enter to continue GetCurrentPayment") #When use this?
# apiRequest("GetCurrentPayment", GetCurrentPayment)
# print(" ")

# print("MAKSA!!")
# input("Press Enter to continue GetPaymentStatus")
# apiRequest("GetPaymentStatus", GetPaymentStatus)
# print(" ")

# PaymentCancel
# input("Press Enter to continue PaymentCancel")
# apiRequest("PaymentCancel", PaymentCancel)
# print(" ")

# unAssignments()
# apiRequest("GetPosList", GetPosList)
