import json
import random
import os
import dotenv
import requests

dotenv.load_dotenv()

payments = {
}

path = "/mnt/"
if os.getenv('LOCAL') == "true":
    path = "./"


if os.path.exists(path+'payments.json'):
    with open(path+'payments.json', 'r') as f:
        payments = json.load(f)
else:
    with open(path+'payments.json', 'w') as f:
        json.dump(payments, f, indent=4)

used = []
if os.path.exists(path+'used.json'):
    with open(path+'used.json', 'r') as f:
        used = json.load(f)
else:
    with open(path+'used.json', 'w') as f:
        json.dump(used, f, indent=4)

if not os.path.exists(path+'promo.json'):
    with open(path+'promo.json', 'w') as f:
        json.dump([], f, indent=4)

HNSaddress = os.getenv('ADDRESS')

names = {
    "pack1": "Pack of 5 Pins: Includes 2x Gold w Silver highlights",
    "pack2": "Pack of 5 Pins: Includes 2x Silver w Gold highlights",
}


def generate_payment(name,email,mobile,address,country,cart,hns,promo=False):
    # Generate a payment object
    payment_id = generate_payment_id()
    if payment_id == "ERROR":
        return False

    finalPrice = str(hns) + '.' + str(payment_id)

    # Fix the cart names
    for item in cart:
        if item['name'] in names:
            item['name'] = names[item['name']]
    
    if promo:
        promo = promo["id"]
        usePromo(promo)


    payment = {
        "name": name,
        "email": email,
        "mobile": mobile,
        "address": address,
        "country": country,
        "hns": hns,
        "ID": finalPrice,
        "cart": cart,
        "promo": promo,
        "status": "Pending"
    }
    finalPriceDolarydoo = float(finalPrice) * 1000000
    payments[finalPriceDolarydoo] = payment
    # Save payments to file
    with open(path+'payments.json', 'w') as f:
        json.dump(payments, f, indent=4)


    payment['HNSaddress'] = HNSaddress
    
    return payment


def check_payments():
    # Get all txs
    data = requests.get(f"https://api.niami.io/address/{HNSaddress}")
    if data.status_code != 200:
        return False
    data = data.json()
    if data['success'] == False:
        return False
    
    data = data['data']
    
    for tx in data:
        for output in tx['outputs']:
            if output['address'] == HNSaddress:
                # Convert to HNS
                outputValue = int(output['value'])
                outputValue = str(float(outputValue))
                
                if outputValue in payments:
                    # Payment found
                    payment = payments[outputValue]
                    if payment['status'] == "Pending":
                        if not finalise_payment(payment):
                            return False
                        payment['status'] = "Paid"
                        with open(path+'payments.json', 'w') as f:
                            json.dump(payments, f, indent=4)
                        print("Payment finalised")
                    
        

def finalise_payment(payment):
    # Send webhook
    url = "https://n8n.woodburn.au/webhook/ea025b12-d002-4f0b-80bb-b39e6452fa66"
    data = payment
    resp = requests.post(url, json=data)
    if resp.status_code != 200:
        print(resp.text)
        return False
    return True

    


def generate_payment_id():
    id = 1
    while True:
        if id not in used:
            used.append(id)
            with open(path+'used.json', 'w') as f:
                json.dump(used, f, indent=4)

            # Return the id padded to 2 digits
            return str(id).zfill(2)
        id +=1
        if id > 75:
            # Send a warning
            requests.post("https://n8n.woodburn.au/webhook/15477afd-60d7-469e-a213-d3bd57234f75", json={"message": "Payment ID is over 75"})

        if id > 99:
            return "ERROR"
        

def getPromo(code):
    with open(path+'promo.json', 'r') as f:
        promos = json.load(f)
    for promo in promos:
        if promo['id'] == code:
            return promo
    return False


def getPromos():
    with open(path+'promo.json', 'r') as f:
        promos = json.load(f)
    return promos

def addPromo(id, constant, percent, uses):
    with open(path+'promo.json', 'r') as f:
        promos = json.load(f)

    for promo in promos:
        if promo['id'] == id:
            return False
        
    
    promos.append({
        "id": id,
        "constant": constant,
        "percent": percent,
        "uses": uses
    })
    with open(path+'promo.json', 'w') as f:
        json.dump(promos, f, indent=4)
    return True

def deletePromo(id):
    with open(path+'promo.json', 'r') as f:
        promos = json.load(f)
    for promo in promos:
        if promo['id'] == id:
            promos.remove(promo)
            with open(path+'promo.json', 'w') as f:
                json.dump(promos, f, indent=4)
            return True
    return False

def usePromo(id):
    with open(path+'promo.json', 'r') as f:
        promos = json.load(f)
    for promo in promos:
        if promo['id'] == id:
            if promo['uses'] == "1":
                promos.remove(promo)
            elif promo['uses'] == "-1":
                return True
            
            uses = int(promo['uses'])
            uses -= 1
            promo['uses'] = str(uses)
            with open(path+'promo.json', 'w') as f:
                json.dump(promos, f, indent=4)
            return True

if __name__ == '__main__':
    for i in range(10):
        generate_payment('Test', 'test@email.com', '123 Test St', [
            {
                'name': 'Test',
                'quantity': 1
            }
        ], 10)

    print(json.dumps(payments, indent=4))
    print(check_payments())