import json
import datetime
import requests

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

images = {
    "pack1": "pins/pack1.jpg",
    "pack2": "pins/pack2.jpg",
}

prices = {
    "pack1": 50,
    "pack2": 50,
}

exchange = {
    'rate': 0,
    'timestamp': 0
}


def cart(cert):
    html = ""
    for item in cert:
        quantity = item['quantity']
        path = item['name']
        if path in names:
            name = names[path]
            image = images[path]
            price = prices[path]
        else:
            name = path
            image = "pins/pack1.jpg"
            price = 50

        hns = usdToHNS(price)
        
        html += "<div class='product'>"
        html += "<div class='row justify-content-center align-items-center'>"
        html += "<div class='col-md-3'>"
        html += f"<div class='product-image'><img class='img-fluid d-block mx-auto image' src='/assets/img/{image}'/></div>"
        html += "</div>"
        html += f"<div class='col-md-5 product-info'><a class='product-name' href='/pins/{path}'>{name}</a></div>"
        html += "<div class='col-6 col-md-2 quantity'>"
        html += f"<label class='form-label d-none d-md-block' for='quantity'>Quantity</label><input id='number{path}' class='form-control quantity-input' type='number' value='{quantity}' /></div>"
        html += f"<div class='col-6 col-md-2 price'><span>US${price}<br>{hns} HNS</span></div>"
        html += "</div>"
        html += script(path)
        html += "</div>"

    return html

def cart_total(cert):
    html = ""
    for item in cert:
        quantity = item['quantity']
        if int(quantity) <= 0:
            continue

        path = item['name']
        if path in names:
            name = names[path]
            image = images[path]
            price = prices[path]
        else:
            name = path
            image = "pins/pack1.jpg"
            price = 50

        hns = usdToHNS(price, True)
        hns = hns * int(quantity)
        hns = "{:,}".format(hns)


        html += f"<div class='item'><span class='price'>{hns} HNS</span>"
        html += f"<p class='item-name'>{name}</p>"
        html += f"<p class='item-description'>{quantity} Packs</p>"
        html += "</div>"
        
    return html

def script(path):
    html = f"""
    <script>
    document.getElementById('number{path}').addEventListener('input', function() {{
        var value = document.getElementById('number{path}').value;
        fetch('/pins/update/{path}', {{
            method: 'POST',
            headers: {{
                'Content-Type': 'application/json'
            }},
            body: JSON.stringify({{
                quantity: value
            }})
        }})

        setTimeout(function() {{
            location.reload()
        }}, 3000)
    }})
    </script>
    """
    return html

def usdToHNS(usd, returnInt=False):
    global exchange
    if exchange['timestamp'] < datetime.datetime.now().timestamp() - 3600:
        response = requests.get('https://api.coingecko.com/api/v3/simple/price?ids=handshake&vs_currencies=usd')
        exchange['rate'] = response.json()['handshake']['usd']
        exchange['timestamp'] = datetime.datetime.now().timestamp()

    hns = usd / exchange['rate']
    
    hns = int(hns / 5) * 5
    if returnInt:
        return int(hns)
    hns = "{:,}".format(hns)
    return hns
    
    
def total_usd(cert,promo):
    total = 0
    for item in cert:
        path = item['name']
        if path in prices:
            total += prices[path] * int(item['quantity'])
        else:
            total += 50 * int(item['quantity'])

    if promo:
        if promo["constant"]:
            total -= int(promo["constant"])
        else:
            total = total - (total * int(promo["percent"]) / 100)

    return total

def total_hns(cert, promo, returnInt=False):
    total = total_usd(cert, promo)
    total = usdToHNS(total,True)

    if returnInt:
        return int(total)
    total ="{:,}".format(total)
    return total


def promoList(promo):
    html = '<ul class="list-group">'
    for item in promo:
        discount = 0
        if item['constant']:
            discount = "$"+item['constant']
        else:
            discount = item['percent'] + '%'
        html += f'<li class="list-group-item"><span>Code: {item["id"]} | {discount} off (Uses Left {item["uses"]})</span><a class="btn btn-primary align-right" role="button" href="/promo/delete/{item["id"]}">Delete</a></li>'
    html += '</ul>'
    return html