{% extends 'base.html' %}
{% block main %}
<h1>{{ title }}</h1>
{% if event %}
<h2>{{ event.name }}</h2>
<h3>{{ event.starts_at }} → {{ event.ends_at }}</h3>
{% else %}
<h2>No ongoing event!</h2>
{% endif %}
<div id="products">
{% for product in products %}
    <button type="button"
            onclick="addProduct({{ product.uid }})">
        <span class="name">{{ product.name }}</span>
        <span class="price">{{ product.price }}</span>
    </button>
{% endfor %}
</div>
<div id="basket">
</div>
<form id="sell" action="/sell"  method="POST">
{% for product in products %}
    <input type="hidden"
           id="prod_{{ product.uid }}"
           name="{{ product.uid }}"
           data-name="{{ product.name }}"
           data-price="{{ product.price }}"
           value="0">
{% endfor %}
    <button type="submit">Print</input>
</form>

<script type="text/javascript">
function addProduct(uid) {
    // This is the hidden input element inside the form. We'll use this DOM
    // element to keep informations about the product, such as the name,
    // the price and the value inside the 'data-' tag.
    form_el = document.getElementById('prod_' + uid)
    basket = document.getElementById('basket')
    basket_el = document.getElementById('basketitem_' + uid)

    form_el.value = parseInt(form_el.value) + 1

    // If there is not a button for the given product inside the basket
    // div we'll create it.
    if (basket_el === null) {
        new_basket_el =
            '<button id="basketitem_' + uid + '"' +
                    'onclick="delProduct(' + uid + ')">' +
                        '1 x ' + form_el.dataset.name +
            '</button>'
        basket.innerHTML += new_basket_el
    } else {
        // Otherwise we'll just update it.
        console.log(form_el.value)
        new_text = form_el.value + ' x ' + form_el.dataset.name
        basket_el.innerText = new_text
    }
}

function delProduct(uid) {
    form_el = document.getElementById('prod_' + uid)
    basket = document.getElementById('basket')
    basket_el = document.getElementById('basketitem_' + uid)

    form_el.value = parseInt(form_el.value) - 1

    if (form_el.value == 0) {
        basket.removeChild(basket_el)
    } else {
        new_text = form_el.value + ' x ' + form_el.dataset.name
        basket_el.innerText = new_text
    }
}
</script>
{% endblock %}