{% extends 'base.html' %}
{% load crispy_forms_tags %}

{% block title %}Price Level{% endblock title %}

{% block search_nav %}
    <form class="d-flex" role="search" action="" method="GET">
        <input autocomplete=off id="search" list="itemname" class="form-control me-2" type="search" placeholder="Search" aria-label="Search" name="q">
        <button class="btn btn-outline-success" type="submit" onclick="search_btn(event)">Search</button>
    </form>
    <datalist id="itemname">
        {% with objects as items %}
        {% for item in items %}
            {% comment %} {{item.FullName}} {% endcomment %}
            <option value="{{item.FullName}}">{{item.FullName}}</option>
        {% endfor %}
        {% endwith %}
{% endblock search_nav %}

{% block body %}
    <form method="POST" onkeydown="return event.key != 'Enter';">
        {% csrf_token %}
        {{form|crispy}}
        <div class="table-responsive">
            <table id="tableId" class="table-sm table-scroll table-bordered border-info table-hover table-striped resizable">
                <thead><tr>
                    <th>FullName</th>
                    <th>SalesPrice</th>
                    <th>Price</th>
                </tr></thead>
                <tbody>
                {% for obj in objects  %}
                    <tr>
                        <td><input type="text" disabled="True" style='width:275px' value="{{obj.FullName}}"></td>
                        <td><input type="text" disabled="True" value={{obj.SalesPrice}}></td>
                        <td><input autocomplete=off class="pricelist" type="text" onfocusout="focusout(this)" data-changed data-fullname="{{obj.FullName}}" 
                        {% if obj.itempricelevel__Price %}
                            data-ori={{obj.itempricelevel__Price}} value={{obj.itempricelevel__Price}}
                        {% else %}
                            data-ori=""
                        {% endif %}>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
        <button type="submit" onclick="clicksubmit(event)">submit</button>
    </form>

<script>
    function search_btn(e) {
        e.preventDefault();
        console.log("search button clicked");
        let searchval = document.getElementById('search');
        //const searchele=document.querySelector('option[value="' + e.target.value + '"]');
        var searchele=document.querySelector('input[data-fullname="' + searchval.value + '"]')
        var searcheleparent=document.querySelector('input[data-fullname="' + searchval.value + '"]').parentNode.parentNode;
        var prevSibling=searcheleparent.previousElementSibling;
        if (prevSibling) {
            prevSibling.scrollIntoView();
        }
        searchele.select();
    }
</script>

<script>
    const pk = {{pk}};
    const datajson={};
    const plist = document.getElementsByClassName('pricelist');
    //console.log(plist.length);
    //console.log(pk);
    const idname = document.getElementById('id_Name');
    const iddesc = document.getElementById('id_Desc');
    //console.log(idname);
    function focusout(e){
        console.log("data-changed="+ e.getAttribute('data-changed')+";");
        if ((parseFloat(e.value).toFixed(2)!=e.getAttribute('data-ori') && e.value != "") ) {
            //if (e.getAttribute('data-ori')) {
            if (e.dataset.ori!=""){
                e.setAttribute('data-changed',  "2");   // 2 => EDIT
                console.log("edit " + e.getAttribute('data-fullname') + ";" + e.getAttribute('data-ori') + "!= "+e.value);
                console.log("data-changed="+ e.getAttribute('data-changed')+";");
            }
            else {
                //e.setAttribute('data-changed',  "1"); // thesame thing with below syntax
                e.dataset.changed = 1;  // 1=> ADD NEW
                console.log("add " + e.getAttribute('data-fullname') + ";" + e.getAttribute('data-ori') + "!= "+e.value);
            }
        } else if ((e.value == null || e.value == "") && e.dataset.ori!=""){
            console.log("dtchange");
            e.setAttribute('data-changed',  "2");   // 2 => EDIT
            console.log("edit " + e.getAttribute('data-fullname') + ";" + e.getAttribute('data-ori') + "!= "+e.value);
        } else if (e.dataset.changed) {
            e.dataset.changed = undefined;
            e.removeAttribute('data-changed');
            console.log(e.getAttribute('data-fullname') + " back to ori " );
        }
        console.log("data-changed="+ e.getAttribute('data-changed')+";");
    }

    function clicksubmit(e){
        e.preventDefault();
        //console.log(pk);
        //console.log(e);

        let dt = [];
        for (let i = 0; i < plist.length; i++) {
            let inputprice = plist[i].value;
            let dtchange = plist[i].dataset.changed;
            let dtfullname = plist[i].dataset.fullname;
            if (dtchange) {
                let dttemp = {
                    FullName : dtfullname,
                    dtchange : dtchange,
                    price : parseFloat(parseFloat(inputprice).toFixed(2)),
                    pk : pk
                };
                //console.log(dttemp);
                dt.push(dttemp);
            }
        }
        console.log(dt);
        const datajson = JSON.stringify(dt);
        console.log(datajson);
        sendform(datajson, idname.value, iddesc.value);
        console.log("data sent");
    }

    function sendform(data, name, desc) {
        fetch('', {
            method: 'POST',
            headers: {
                'X-CSRFToken': csrftoken,
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                'data': data,
                'pk' : pk,
                'Name' : name,
                'Desc' : desc,
            }),
            redirect: "follow", // follow, manual, error
        })
        .then(response => {
            if (response.redirected) {
              window.location.replace(response.url); 
            // creates the second request, and change the content
              return; 
            };
        })
    }

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');
    console.log(csrftoken);
</script>

{% endblock body %}