{% extends "base.html" %}
{%block title%}
<title>Admin - Langhuan</title>
{%endblock%}

{%block content%}
<div class="row p-3 pl-5 pr-5">
    <h2 class="col-sm-12 mb-2">
        <i class="fas fas fa-house-user"></i>
        Admin: <strong>Lang</strong><span class='text-warning'>Hu</span><span class='text-danger'>an</span>
    </h2>

    <div class="col-sm-6 p-3">
        <h3>
            <i class="fas fa-table"></i>
            Progress</h3>
        
        <div class="row">
            <div class="btn-group m-2">
                <a href="/result" class="btn-primary btn" download="langhuan_result.json">
                    <i class="fas fa-download">

                    </i>
                    Download as JSON</a>

                <button class="btn btn btn-warning" id="force_save">
                    <i class="fas fa-save">

                    </i>
                    Force Save
                </button>
            </div>

        </div>
        <div class="row">
            <table class="table">
                <tr>
                    <th>
                        Total Proccessed
                    </th>
                    <td id="total_processed">
                        0
                    </td>
                </tr>
            </table>
            <div id="stats_by_user">

            </div>
        </div>
    </div>

    <div class="col-sm-6 p-3">
        <h3>
            <i class="fas fas fa-ticket-alt"></i>
            Label Options</h3>
        <div class="input-group">
            <input type="text" id="add_option" placeholder="Input New Label Option" class="form-control">
            <button class="btn btn-primary " id="add_option_btn">
                <i class="fas fa-plus-square"></i> New
            </button>
        </div>

        <div id="options" class="row">

        </div>

    </div>
</div>

{%endblock%}


{%block tail_js%}
{{super()}}

<script defer>
    const flavors = [
        "primary", "danger", "success", "warning", "dark", "secondary", "info"
    ]

    const get_param = (k) => {
        const urlParams = new URLSearchParams(window.location.search);
        const param = urlParams.get(k);
        return param
    }

    const add_option = async (e) => {
        var option = document.querySelector("#add_option").value

        if (option == "") {
            console.error("option not set")
            return
        } else {
            var admin_key = get_param("adminkey")
            var dt = { option }
            if (admin_key) {
                dt.adminkey = admin_key
            }
            fetch("/add_option",
                {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify(dt)
                }
            ).then(res => res.json())
                .then(data => {
                    if (data.option == option) {
                        location.reload()
                    }
                }).catch(console.error)
        }
    }

    const delete_option = async (e, option) => {
        console.log(option)

        var admin_key = get_param("adminkey")
        var dt = { option }
        if (admin_key) {
            dt.adminkey = admin_key
        }
        fetch("/delete_option",
            {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(dt)
            }
        ).then(res => res.json())
            .then(data => {
                if (data.option == option) {
                    location.reload()
                }
            }).catch(console.error)
    }

    const visualize_options = (options) => {

        var op_box = d3.select("#options")
            .selectAll("div").data(options)
            .enter().append("div")

        op_box
            .attr("class", "col-sm-12 m-1")

        var del_btns = op_box.append("button")
            .attr("class", "btn btn-danger btn-sm")
            .on("click", delete_option)

        del_btns
            .append("i")
            .attr("class", "fas fa-backspace")

        op_box.append("span").attr("class", "p-2").text(d => { return d })

    }

    const admin_post = (url, resolve, error_handler) => {
        var admin_key = get_param("adminkey")
        var data = {}
        if (admin_key) { data.adminkey = admin_key }
        fetch(url, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(data)
        }).then(res => res.json())
            .then(resolve)
            .catch(error_handler)
    }

    const set_options = async () => {
        admin_post("/get_options",
            visualize_options,
            console.error
        )
    }

    const save_progress = async (e, d) => {
        admin_post(
            "/save_progress",
            d => {
                document.querySelector("#total_processed")
                    .innerHTML = d.so_far
            },
            console.error
        )
    }

    document.querySelector('#force_save')
        .addEventListener("click", save_progress)

    const stats_by_user = async () => {
        admin_post(
            "/stats",
            by_user => {
                var data = []
                var total_entries = 0;
                for(var user_id in by_user){
                    data.push({...by_user[user_id], user_id})
                    total_entries+=by_user[user_id].entry_ct
                }
                document.querySelector("#total_processed")
                    .innerText = total_entries

                var user_block = d3.select("#stats_by_user")
                .selectAll("div")
                .attr("class", "user_block")
                .data(data).enter().append("div")

                user_block.append("h6").text(d=>{
                    return `Summary of user: ${d.user_id}`
                })

                var user_table = user_block.append("table")
                .attr("class","table")

                var user_entry_row = user_table.append("tr")
                user_entry_row.append("th").text("User Entries")
                user_entry_row.append("td").text(d=>d.entry_ct)

                var user_skipped_row = user_table.append("tr")
                user_skipped_row.append("th").text("Sipped Entries")
                user_skipped_row.append("td").text(d=>d.skip_ct)
            
            },
            console.error
        )
    }
    set_options()
    stats_by_user()

    document.querySelector("#add_option_btn").addEventListener("click", add_option)
</script>
{%endblock%}