{% extends "base.html" %}
{% block title %}{{ config['APP_TITLE'] }}{% endblock %}
{% block head %}
{{ super() }}

<style>
    a {
        color: inherit;
        text-decoration: none;
        /* no underline */
    }
</style>
{% endblock %}
{% block content %}


<h2 class="mt-3"> {{ repo_name }} </h2>

<label class="font-weight-bold form-label" for="submitText">Search across all spreadsheets:</label>
<form id="submitText" class="d-flex">
    <input id="inputText" name="inputText" value="" placeholder='search terms'
        class="form-control me-2 d-inline-block w-auto" />
    <button type="submit" id="inputBtn" name="input" value="search" class="btn btn-outline-success me-2"
        onclick="return submitForm(this)">
        <i class=" fas fa-search"></i> Search
    </button>
    <button type="submit" id="show-all-assigned" name="show_all_assigned" value="show_assigned"
        class="btn btn-outline-warning" onclick="return submitForm(this)">
        <i class="fas fa-search-plus"></i> Show all assigned to me
    </button>
</form>

<div class="row">
    <div class="col-md-12">
        <div id="contentTable" class="table table-bordered table-striped table-hover table-sm mt-2"
            style="font-size: 0.8em; width: 100%;"></div>
        </div>
    </div>
</div>


<!-- //tabulator: -->
<!-- always up-to-date tabulator CDN -->
<link href="https://unpkg.com/tabulator-tables@4.9.3/dist/css/tabulator_simple.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.9.3/dist/js/tabulator.min.js"></script>


<!-- bootstrap 4 theme -->
<link href="https://unpkg.com/tabulator-tables@4.9.3/dist/css/bootstrap/tabulator_bootstrap4.min.css" rel="stylesheet">


{% set folder_parts = folder_path.split('/') | select | list %}
<ul class="list-unstyled">
    <li class="p-1">
        <a href="{{ url_for('main.repo', repo_key=repo_name) }}">
            {%if not folder_path %}<strong>{% endif %}
            <i class="fa-solid fa-folder-open me-2" style="color: orange"></i>{{ repo_name }}
            {%if not folder_path %}</strong>{% endif %}
        </a>
    </li>

    {% for part in folder_parts %}
    <li style="margin-left: {{ loop.index * 20 }}px" class="p-1">
        <a
            href="{{ url_for('main.repo', repo_key=repo_name, folder_path=(folder_parts[:loop.index0 + 1] | join('/')) ) }}"
            >
            {%if loop.last %}<strong>{% endif %}
            <i class="fa-solid fa-folder-open me-2" style="color: orange"></i>{{ part }}
            {%if loop.last %}</strong>{% endif %}
    </li>
    {% endfor %}

    {% for dir in directories if not dir.startswith('.') and dir != 'scripts' %}
    <li style="margin-left: {{ (folder_parts | length + 1) * 20 }}px" class="p-1">
        <a href="{{url_for('main.repo', repo_key=repo_name, folder_path= folder_path+'/'+dir)}}">
            <i class="fa-solid fa-folder me-2" style="color: orange"></i>
            {{ dir }}
        </a>
    </li>
    {% endfor %}
    {% for spr in spreadsheets if not spr.startswith('.') %}
    <li style="margin-left: {{ (folder_parts | length + 1) * 20 }}px" class="p-1">
        <a
            href="{{ url_for('edit.edit', repo_key=repo_name, path=([folder_path, spr] | reject('==', '') | join('/'))) }}">
            <i class="fa-regular fa-file-excel me-2" style="color: green"></i>
            {{spr }}
        </a>
    </li>

    {% endfor %}
</ul>

<br></br>
<label style="color: #1b1a1a;" class="font-weight-bold" for="idList">Visualise a selection of ID's:</label>
<form id="idSubmission">
    <textarea id="idList" form="idSubmission" class="form-control" name="idList" value=""
        placeholder='list of IDs separated by spaces and/or new lines' rows="3"></textarea>
    <input id="visualise-IDs" type="submit" class="btn btn-outline-success mt-2"></input>
</form>

<script type="text/javascript">
    var URL_PREFIX = '{{config["URL_PREFIX"]}}';
    var initials = '{{user_initials}}';

    //get all rows with "Show all assigned to me"
    async function sendDataWithLogin() {
        const form = document.getElementById("submitText");

        // Bind the FormData object and the form element
        const FD = new FormData(form);
        // FD.append('initials', 'ZZ'); //test
        FD.append('initials', '{{user_initials}}');
        FD.append('repoName', '{{repo_name}}');

        const response = await (await fetch(URL_PREFIX + "/searchAssignedToMe", {
            body: FD,
            method: "POST"
        })).json()
        const results = response['searchResults']
        const resultsArray = JSON.parse(results);
        // $("#resultsHeader").text("RESULTS - click on a row to open its spreadsheet");
        const type = "initials";
        createTable(resultsArray, type);
    }

    //get all rows with search terms
    async function sendData() {
        const form = document.getElementById("submitText");

        // Bind the FormData object and the form element
        const FD = new FormData(form);
        FD.append('repoName', '{{repo_name}}');

        const response = await (await fetch(URL_PREFIX + '/search', {
            body: FD,
            method: "POST"
        })).json()

        const results = response['searchResults'];
        const resultsArray = JSON.parse(results);
        // $("#resultsHeader").text("RESULTS - click on a row to open its spreadsheet");
        const type = "search";
        createTable(resultsArray, type);
    }

    function submitForm(button) {
        (async () => {
            let dialog = bootbox.dialog({
                message: '<p class="text-center mb-0"><i class="fas fa-spin fa-cog"></i> SEARCHING...</p>',
                closeButton: true
            });
            let dialogShown$ = new Promise((resolve, _) => {
                dialog.on('shown.bs.modal', () => resolve())
            });
            // let $resultsHeader = $("#resultsHeader");
            // $resultsHeader.text("SEARCHING...");
            // $resultsHeader.show();

            try {
                if (button.value === "search") {
                    await sendData();
                } else if (button.value === "show_assigned") {
                    await sendDataWithLogin();
                }
            } catch (e) {
                bootbox.alert("Something went wrong");
                console.log(e);
            }

            await dialogShown$;
            dialog.modal("hide")
        })()


        return false;
    }

    window.addEventListener("load", function () {
        // console.log("loaded");
        // $("#resultsHeader").hide();
        // Access the form2 element...
        const form2 = document.getElementById("idSubmission");

        // ...and take over its submit event.
        form2.addEventListener("submit", function (event) {
            event.preventDefault();
            const FD2 = new FormData(form2);
            console.log(FD2);
            console.log("visualise ID's clicked");
            var data = FD2; //todo: build data from here
            console.log("submitted " + FD2);
            form2.setAttribute("method", "post");
            form2.setAttribute("action", URL_PREFIX + "/openVisualiseAcrossSheets");
            form2.setAttribute("target", 'VisualisationWindow');
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = "repo";
            input.value = "{{repo_name}}";
            form2.appendChild(input);
            var input2 = document.createElement('input');
            input2.type = 'hidden';
            input2.name = "data";
            input2.value = JSON.stringify(data);
            form2.appendChild(input2);
            form2.target = 'VisualisationWindow';
            form2.submit();

        });

    });

    function createTable(responseData, type) {
        if (type == "search") {
            if (responseData.length < 1) {
                // document.getElementById("resultsHeader").innerHTML = "No Results";
            } else {
                // document.getElementById("resultsHeader").innerHTML = "RESULTS - click on a row to open its spreadsheet:";
            }
            var table = new Tabulator("#contentTable", {
                data: responseData,

                columns: [ //Define Table Columns
                    { title: "Class ID", field: "class_id", formatter: "textarea", width: "120" },
                    { title: "Definition", field: "definition", formatter: "textarea" },
                    { title: "Label", field: "label", formatter: "textarea" },
                    { title: "Parent", field: "parent", formatter: "textarea" },
                    { title: "Repo", field: "repo", formatter: "textarea", width: "80" },
                    { title: "Spreadsheet", field: "spreadsheet", formatter: "textarea", width: "360" },
                ],

                layout: "fitColumns",
                pagination: "local",
                paginationSize: "5",
                paginationSizeSelector: [5, 10, 25, 50, 100, true],
                paginationCounter: "rows",

                // various ways to deal with user opening linked sheets in tabulator: https://github.com/olifolkerd/tabulator/issues/153

                //todo: different rowClick for "initials" type
                rowClick: function (e, row) {
                    var data = row.getData();
                    if (data['label'] != null && data['label'] != "") {
                        openSheet(type, data["repo"], data["spreadsheet"], data['label']);
                        console.log("label: " + data['label']);
                    } else {
                        openSheet(type, data["repo"], data["spreadsheet"], '');
                        console.log("no label");
                    }
                },
            });
        } else if (type == "initials") {
            console.log(type);
            console.log(responseData);
            if (responseData.length < 1) {
                document.getElementById("resultsHeader").innerHTML = "No Results";
            } else {
                document.getElementById("resultsHeader").innerHTML = "RESULTS - click on a row to open its spreadsheet:";
            }
            var table = new Tabulator("#contentTable", {
                data: responseData,

                columns: [ //Define Table Columns
                    { title: "Class ID", field: "class_id", formatter: "textarea", width: "120" },
                    { title: "Definition", field: "definition", formatter: "textarea" },
                    { title: "Label", field: "label", formatter: "textarea" },
                    { title: "Parent", field: "parent", formatter: "textarea" },
                    { title: "Repo", field: "repo", formatter: "textarea", width: "80" },
                    { title: "Spreadsheet", field: "spreadsheet", formatter: "textarea", width: "360" },
                ],

                layout: "fitColumns",
                pagination: "local",
                paginationSize: "5",

                //different rowClick for "initials" type
                rowClick: function (e, row) {
                    var data = row.getData();
                    openSheet(type, data["repo"], data["spreadsheet"], initials);
                },
            });
        }
    }

    function openSheet(type, repo, sheet, go_to_row) {
        console.log(sheet + " " + sheet + " " + go_to_row + " " + type);

        window.location.href = URL_PREFIX + `/direct?type=${type}&repo=${repo}&sheet=${sheet}&go_to_row=${go_to_row}`;
    }


</script>


{% endblock %}