{% extends "webpage/base.html" %}
{% load static %}
{% load stats_extras %}
{% load webpage_extras %}

{% block content %}
<script src="/static/dubletten_tool/js/autocomplete.js"></script>
<link href="/static/dubletten_tool/css/autocomplete.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="/static/dubletten_tool/css/main_dubletten.css" type="text/css">


<!-- <div class="row w-100 justify-content-center">
<h1 class="text-center w-100">Dubletten Tool</h1>
</div> -->

<div class="container-fluid w-100">
    <div class="row w-100 pt-5 pb-3">
        <div class="col-md-3">
            <div id="manu_navigation">
                <ul class="nav nav-tabs" id="myTab" role="tablist">
                    <li class="nav-item" role="presentation">
                      <a class="nav-link active" id="groups-tab" data-toggle="tab" href="#groups_section" role="tab">Groups</a>
                    </li>
                    <li class="nav-item" role="presentation">
                      <a class="nav-link" id="singles-tab" data-toggle="tab" href="#singles_section" role="tab">Singles</a>
                    </li>
                    <li class="nav-item" role="presentation">
                      <a class="nav-link" id="marked-tab" data-toggle="tab" href="#marked_section" role="tab">Marked</a>
                    </li>
                  </ul>
            </div>
            <!-- <h2 class="pl-4">Groups</h2> -->
        </div>
        <div class="col-md-4 pl-4">
            <span class="d-flex justify-content-between align-items-center">  
                <h2 class="pl-4">Selected</h2>
                <button class="btn btn-primary group_action_button m-0" onclick="mergeGroups()" id="button_merge">merge all</button>
                <button class="btn btn-primary group_action_button m-0" onclick="createNewGroup()" id="cross_group_create_button">group selections</button>
            </span>
        </div>
        <div class="col-md-5 pl-4">
            <h2 class="pl-4">Detail / Suggestions</h2>
        </div>
    </div>
  
    <div class="row w-100">
        <div class="col-md-3">
            <div class="tab-content" id="myTabContent">
                <div class="tab-pane fade show active" id="groups_section" role="tabpanel">  
                    <span class="d-flex justify-content-center align-items-center">
                        <input class="form-control mr-4 rounded-right" type="search" placeholder="Search for Groups" id="search_groups">
                    </span>
                    <span class="d-flex px-1 my-2 justify-content-start align-content-center" id="group_label_span"><label class="mr-2">Count:</label><label id="group_count_container">0</label></span>

                     <div class="container-fluid mt-5" style="overflow-y: scroll; height: 80vh;" id="group_list_container">
  
                   </div>
                </div>
                <div class="tab-pane fade" id="singles_section" role="tabpanel">
                        <span class="d-flex px-1 my-2 justify-content-start align-content-center"><input aria-label="Search" class="form-control mr-4 rounded-right" id="input_search"
                            placeholder="Name"
                            type="search">
                            <input aria-label="Search" class="form-control mr-4 rounded-right" id="filter_first_name"
                            placeholder="First Name"
                            type="search"></span>
                            <span class="d-flex px-1 my-2 justify-content-start align-content-center"><label class="mr-2">Count:</label><label id="filtered_count">0</label></span>
                                <div class="container-fluid pt-2" style="overflow-y: scroll; height: 80vh;">

                            <ul class="list-group mt-3" id="singles_container">
                    <!-- <ul class="list-group" id="all_singles_list">
                    {% for s in singles %}
                    <li class="list-group-item single-list-item list-group-item-sm d-flex justify-content-between align-items-center" id="single_list_item_{{s.id}}">
                        {{s.person.name}}, {{s.person.first_name}}
                    </li>
                </ul>
                    {% endfor %} -->
                    </ul>
                </div>
                </div>
                <div class="tab-pane fade" id="marked_section" role="tabpanel" >
                    Not implemented yet
                </div>
         
    </div>
        </div>
        <div class="col-md-4 pl-4 pb-5" id="relations_section" style="width: 100%; overflow-y: scroll; height: 80vh;">
        <div class="w-100 m-0 p-0" id="relations_group_section"></div>
        <h3 class="h3" id="singles_header">Singles</h3>

        <div class="w-100 m-0 p-0" id="relations_single_section"></div>

        
        </div>
        <div class="col-md-5 pl-4 pb-5" id="detail_section" style="width: 100%; overflow-y: scroll; height: 80vh;">

    </div>
</div>
<script>
    let SELECTED_MEMBERS = {};
    let SELECTED_GROUPS = [];
    let SELECTED_SINGLES = [];
    let BTN_MERGE = $("#button_merge");

    function checkSinglesHeader(){
        if (SELECTED_SINGLES.length > 0){
            $("#singles_header").show();

        } else {
            $("#singles_header").hide();

        }
    }

    function isGroupDisplayed(id){
        console.log($(`#group_data_${id}`))
        if ($(`#group_data_${id}`).length >= 1){
            return true;
        } else {
            return false;
        }
    }

    function toggleItemSelect(id){
        console.log("clicked, id is:", id)
        let target_item = document.getElementById(`li_group_${id}`);
        console.log(target_item)
        if (target_item.style.backgroundColor != "lightblue") {
            target_item.style.backgroundColor = "lightblue";
            SELECTED_GROUPS.push(id);
           
            
        console.log(isGroupDisplayed(id));
        getGroupAjax(id);
        } else {
            $(`#group_data_${id}`).remove();
            target_item.style.backgroundColor = "white";
            console.log(isGroupDisplayed(id));
            SELECTED_GROUPS.pop(id);
    
        }
        console.log("clicked: ", id);
        SELECTED_MEMBERS[id]=[];
        console.log("Reset Selected Memebers", SELECTED_MEMBERS);
        checkMergeButton();

    }

    function checkMergeButton(){
        if (SELECTED_GROUPS.length > 1){
            BTN_MERGE.show();
            } else {
            BTN_MERGE.hide();    
            }
    }

    function getGroupAjax(id, update=false){
        let url = "{% url 'dubletten_tool:get_group_ajax' g_id='12345' %}".replace("12345", id);
        console.log("Get Group Ajax Called");
        console.log(url);
        $.ajax({
            url: url,
            type:"GET",
            beforeSend: function (request) {
                let csrftoken = getCookie("csrftoken");
                request.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function (data){
                if (update){
                    $(`#group_data_${id}`).replaceWith(data.html);
                } else {
                if (!isGroupDisplayed(id)){
                $("#relations_group_section").append(data.html);
                } else {
                    $(`#group_data_${id}`).replaceWith(data.html);
                }
              
            }
        }

        })
    }

    function addGroupToList(id, name, count){
        $("#all_groups_list").append(
            `<li class="list-group-item group_list_item_ list-group-item-sm d-flex justify-content-between align-items-center" onclick="toggleItemSelect(${id})" id="li_group_${id}">${id} ${name}
            <span class="badge badge-primary badge-pill" id="group_count_badge_${id}">${count}</span> </li>`
        )

    }

    function updateGroupCountBadges(id, count){

        if (count === 0){
            $(`#li_group_${id}`).remove();
        }
        else {
        let badge = $(`#group_count_badge_${id}`)
        badge.html(count)
        }
    }

    function createNewGroup(){
        let url = "{% url 'dubletten_tool:create_new_group' %}";
        let name = prompt("Please Enter Name for New Group")

        let data = JSON.stringify({"data":SELECTED_MEMBERS, "singles":SELECTED_SINGLES, "new_name":name});
        $.ajax({
            url:url,
            type:"POST",
            beforeSend: function (request){
                let csrftoken = getCookie("csrftoken");
                request.setRequestHeader("X-CSRFToken", csrftoken);
            },
            dataType:"json",
            data: {"DATA":data},
            success: function(response){
                res = response.data;
                addGroupToList(res.new_group_id, res.new_group, res.new_group_count)
                let cross_btn = $("#cross_group_create_button");

                
                for([k, v] of Object.entries(res.group_updates)){
                    console.log(k,v);
                    updateGroupCountBadges(k, v);
                    if (v > 0){
                    getGroupAjax(k, true);
                    } else {
                        $(`#group_data_${k}`).remove();

                    }
                }
                console.log("former singles")
                console.log(response.data.former_singles)
                response.data.former_singles.forEach((s) => {
                    //console.log("for each called for: ", s, "section:", `single_data_${s}`);
                    $(`#single_data_${s}`).remove();

                })

                SELECTED_MEMBERS = {};
                cross_btn.hide();


            }
        })
    }
</script>

<script>
    function removeMember(group_id, per_id){
        let url = "{% url 'dubletten_tool:remove_member' group_id='111111' per_id='222222' %}".replace("111111", group_id).replace("222222", per_id);

        console.log("in remove Member");
        console.log(url);

        let test = confirm(`do you really want to delete: Member ${per_id} from group: ${group_id} ?`);

        if (test){
            $.ajax({
                url: url, 
                type:"GET",
                beforeSend: function (request){
                let csrftoken = getCookie("csrftoken");
                request.setRequestHeader("X-CSRFToken", csrftoken);
            },success: function(data){
                console.log(JSON.stringify(data));
                updates = data.data;
                for([k, v] of Object.entries(updates)){
                    if (v != 0){
                        getGroupAjax(group_id, true);
                    } else {
                        $(`#group_data_${k}`).remove();
                        
                    }
                    updateGroupCountBadges(k, v);

                }



            }
            })
        }
    }
</script>

<script>
    function mergeGroups(){
        let url = "{% url 'dubletten_tool:merge_groups' %}";
        console.log("Selected Groups is:", SELECTED_GROUPS);
        console.log("SELECTED_GROUPS after adding singles is:", SELECTED_GROUPS)
        name = prompt("Enter new name for Merged Group:");
        data = JSON.stringify({"groups":SELECTED_GROUPS, "singles": SELECTED_SINGLES, "new_name":name})
         $.ajax({
            url:url,
            type:"POST",
            dataType: "json",
            data: {"DATA":data},
            beforeSend: function (request){
                let csrftoken = getCookie("csrftoken");
                request.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function(data){
            alert(JSON.stringify(data));       
            addGroupToList(data.add[0], data.add[1], data.add[2]);
            $("#relations_group_section").empty();
            $("#relations_single_section").empty();

            getGroupAjax(data.add[0]);
            SELECTED_GROUPS = []
            SELECTED_MEMBERS = {}
            SElECTED_SINGLES = []
            data.remove.forEach(el => { $(`#li_group_${el}`).remove();})   
            checkMergeButton();            
            
            //todo: create listspan; empty selection_section, request newly created group     
            }
        })
    }
</script>

<script>
    function manageSelection(group_id, member_id){

        if (SELECTED_MEMBERS[group_id]){
            console.log("group existed in selected members");
            SELECTED_MEMBERS[group_id].push(member_id);
        }else{
            console.log("group didn't exist in selected members");
            SELECTED_MEMBERS[group_id] = [member_id];
        }
        }
    
    

    function toggleSingleSelect(id){
        console.log("clicked Toggle Single Select for id: ", id);

        let target_item = document.getElementById(`single_list_item_${id}`);


        if (target_item.style.backgroundColor != "lightblue") {
            target_item.style.backgroundColor = "lightblue";
            SELECTED_SINGLES.push(id);
           
        getSinglesAjax(id);
        } else {
            $(`#single_data_${id}`).remove();
            target_item.style.backgroundColor = "white";
            SELECTED_SINGLES.pop(id);
    
        }
        console.log("clicked: ", id);
        checkMergeButton();
        checkSinglesHeader()


    }

    function getSinglesAjax(single_id){
        let url = "{% url 'dubletten_tool:get_single_ajax' s_id='123456' %}".replace("123456", single_id);

        $.ajax({
            url: url, 
            type: "GET",
            beforeSend: function (request){
                let csrftoken = getCookie("csrftoken");
                request.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function(data){
                console.log("data arrived as: ", data.html)
                $("#relations_single_section").append(data.html);

        }})
    }
    

    function toggleMemberSelect(group_id, member_id){
        let el = event.target;
     
        //let action_span = $(`#span_group_actions_${group_id}`);
        let cross_btn = $("#cross_group_create_button");
        if (el.style.backgroundColor != "lightblue") {
            manageSelection(group_id, member_id);

        el.style.backgroundColor="lightblue";
        //let test = action_span.children(".group_action_button").show();
        cross_btn.show();
        }
        else{
            el.style.backgroundColor="inherit";
            SELECTED_MEMBERS[group_id].pop(member_id);
            if (SELECTED_MEMBERS[group_id].length == 0){
                delete SELECTED_MEMBERS[group_id];
                //let test = action_span.children(".group_action_button").hide();
                if (SELECTED_SINGLES.length == 0 && Object.keys(SELECTED_MEMBERS).length <= 1){
                cross_btn.hide();}

            }
        }

        console.log(SELECTED_MEMBERS);
    }
</script>


<script>

    let singlesData = "{{singles|escapejs}}";
    
    function filterSingles(){
        let text = $("#input_search").val();
        text = text.toLowerCase();
        let filteredData = singlesData.filter((n) => 
        n[1].toLowerCase().startsWith(text)
        ); 

        renderSingles(filteredData);
    }
    
</script>

<script>
    function getSinglesData(){
        let url= "{% url 'dubletten_tool:get_singles' %}";
        $.ajax({
            url: url,
            type:"GET",
            beforeSend: function (request){
                let csrftoken = getCookie("csrftoken");
                request.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function(data){
                singlesData = data.singles;
                console.log("singlesData set");
                renderSingles(singlesData);
            }
        })
    }

    function renderSingles(data){
        let container = $("#singles_container");
        let count = data.length

        $("#filtered_count").text(count);

        container.empty();

        data.forEach((el) => {
            container.append(`<li class="list-group-item single-list-item list-group-item-sm d-flex justify-content-between align-items-center" id="single_list_item_${el[0]}" onclick="toggleSingleSelect(${el[0]})">
                         ${el[1]}, ${el[2]}</li>`)
        })

        // for ([k, v] of Object.entries(data)){
        //     container.append(`<li class="list-group-item single-list-item list-group-item-sm d-flex justify-content-between align-items-center" id="single_list_item_${k}">
        //                 ${v.name}, ${v.first_name}
        //             </li>`)
        // }
    }

    $("#input_search").on("keyup", function(e){
        // if ($("#input_search").val().length >= 2){
        // filterSingles();
        // }
        if (e.key === "Enter" || e.keyCode === 13) {
        //filterSingles();
        //let text = $("#input_search").val();

        requestSingles();
    }})

    $("#search_groups").on("keyup", function(e){
        // if ($("#input_search").val().length >= 2){
        // filterSingles();
        // }
        if (e.key === "Enter" || e.keyCode === 13) {
        //filterSingles();
        //let text = $("#input_search").val();

        requestGroups();
    }})

    function getInputVal(){
        let name = $("#input_search").val();
        let first_name = $("#filter_first_name").val();

        name = name ? name : false;
        first_name = first_name ? first_name : false;
        
        if (name) {
        name = name.replace(" ", "__");
        } 
        if (first_name) {
        first_name = first_name.replace(" ", "__");
        }
        return [name, first_name]

    }

    $("#filter_first_name").on("keyup", function(e){
        // if ($("#input_search").val().length >= 2){
        // filterSingles();
        // }
        if (e.key === "Enter" || e.keyCode === 13) {
        //filterSingles();
        //let text = $("#filter_first_name").val();

        requestSingles();
    }})

    function requestSingles(){
        let values = getInputVal();

        if (true){
            let url = "{% url 'dubletten_tool:get_singles' val_name='xxxxx' val_first='yyyyy'%}".replace("xxxxx", values[0]).replace("yyyyy", values[1]);
            $.ajax({
                url: url,
                type: "GET",
                beforeSend: function (request){
                let csrftoken = getCookie("csrftoken");
                request.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function (response) {
                renderSingles(response.singles);
           }

            })
        } 

    }

    function requestGroups(){
        let value = $("#search_groups").val();

        if (value.length >= 1){

        if (true){
            let url = "{% url 'dubletten_tool:get_groups' val='xxxxx' %}".replace("xxxxx", value);
            $.ajax({
                url: url,
                type: "GET",
                beforeSend: function (request){
                let csrftoken = getCookie("csrftoken");
                request.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function (response) {
                let container = $("#group_list_container");
                container.html(response.html);
                $("#group_count_container").html(response.group_count)
           }

            })
        }
    } 


    }

    
</script>
{% endblock %}

