{{define "modal-manage-versions"}}
<div class="modal fade" id="modal-manage-versions" tabindex="-1" role="dialog" aria-labelledby="modal-manage-versions-label" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modal-manage-versions-label"><i class="fa fa-wrench" aria-hidden="true"></i> Manage Variants and Versions</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <wrapper>
                <div class="modal-body" style="width: 50%;float: left;border-right: 1px solid #e9ecef;">
                    <h5>Variants</h5>
                    <div class="row">
                        <div class="col-12">
                            <div class="input-group">
                                <input type="text" class="form-control" id="inputProjectVariant" placeholder="e.g. Windows 10" aria-label="e.g. Windows 10">
                                <span class="input-group-btn">
                                    <button id="buttonAddProjectVariant" class="btn btn-secondary" type="button">Add</button>
                                </span>
                            </div>
                        </div>
                    </div>
                    <br>
                    <ul id="variantList" class="list-group">
                    </ul>
                </div>
                <div class="modal-body" style="width: 50%;float: right;border-left: 1px solid #e9ecef;">
                    <h5>Versions</h5>
                    <div class="row">
                        <div class="col-12">
                            <div class="input-group">
                                <select id="projectVariantSelect" class="form-control custom-select" onchange="showVersions();">
                                    <option value="none">Select a variant...</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <br>
                    <div class="collapse"  id="collapseVersions">
                        <div class="row">
                            <div class="col-12">
                                <div class="input-group">
                                    <input type="text" class="form-control" id="inputProjectVersion" placeholder="e.g. 1.0.3" aria-label="e.g. 1.0.3">
                                    <span class="input-group-btn">
                                    <button id="buttonAddProjectVersion" class="btn btn-secondary" type="button">Add</button>
                                </span>
                                </div>
                            </div>
                        </div>
                        <br>
                        <ul id="versionList" class="list-group">
                        </ul>
                    </div>
                </div>
            </wrapper>
            <div class="modal-footer">
                <button id="buttonSaveVariants" type="button" class="btn btn-primary">Save settings</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>

    <script src="/static/js/util/common.js"></script>
    <script type='text/javascript'>

        var xmlhttp = new XMLHttpRequest();
        // selectedVariant is the key of the currently selected variant in the drop down menu as string
        var selectedVariant;

        //project variant data
        var projectVersionData;
        var urlVersions = getProjectURL().appendSegment("versions").toString();

        xmlhttp.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
                projectVersionData = JSON.parse(this.responseText);
                fillVariants(projectVersionData, "#projectVariantSelect");
            }
        };
        xmlhttp.open("GET", urlVersions, true);
        xmlhttp.send();

        // fill Variants gets a map with variants and adds them to the drop down menu with the selectorID
        function fillVariants(variantMap, selectorID) {
            $('#inputTestCaseSUTVariants').empty();
            $("#variantList").empty();
            $.each(variantMap, function(key,variant) {
                addVariant(variant, selectorID);
            });
        }

        // addVariant adds a variant to the drop down menu with variants
        function addVariant(variant, selectorID) {
            var selector = $(selectorID);
            var selectedValue = selector.val();
            selector.append($("<option></option>")
                    .attr("value",variant.Name)
                    .text(variant.Name));
            selector.value = selectedValue;
            //list
            var list = $('#variantList');
            var listElement = ($("<li></li>")
                 .attr("class","list-group-item")
                 .attr("style","display:flex;")
                 .html('<span style="width:50%;">'+variant.Name+'</span>'));
            var deleteButton = ($("<button></button>")
                 .attr("class","btn btn-danger ml-auto list-line-item btn-sm buttonDeleteVariant")
                 .attr("id","del-var-" + variant.Name)
                 .attr("type","button")
                 .html('<i class="fa fa-trash-o" aria-hidden="true"></i>\n' +
                         '<span class="d-none d-sm-inline"> Delete</span>'));
                 deleteButton.click(function (event) { buttonDeleteVariant(event); });
            var variantDeleteConfirmButton = ($("<button></button>")
                 .attr("class","btn btn-danger ml-auto d-none list-line-item btn-sm buttonDeleteVariantConfirm")
                 .attr("id","delConfirm-var-" + variant.Name)
                 .attr("type","button")
                 .html('<i class="fa fa-check" aria-hidden="true"></i>\n' +
                         '<span class="d-none d-sm-inline"> Confirm delete</span>'));
            variantDeleteConfirmButton.click(function (event) { buttonDeleteVariantConfirm(event); });
            listElement.append(deleteButton);
            listElement.append(variantDeleteConfirmButton);
            list.append(listElement);
        }



        /* Adding a handler for the enter key to add a variant*/
        $("#inputProjectVariant").keydown(function(event){
            if(event.keyCode === 13){
                event.preventDefault();
                $("#buttonAddProjectVariant").click();
            }
        });

        /* attach a handler to the add test cases form submit button */
        $("#buttonAddProjectVariant").click(function(event){
            var variantKey = $("#inputProjectVariant").val().trim();
            if (projectVersionData === null) {
                projectVersionData = {};
            }
            if((variantKey !== "")&&!(variantKey in projectVersionData)) {
                projectVersionData[variantKey] = JSON.parse('{"Name":"'+variantKey+'","Versions":"'+[]+'"}');
                projectVersionData[variantKey].Versions = [];
                addVariant({Name:variantKey,Versions:{}}, "#projectVariantSelect");
                // Clear text field
                $("#inputProjectVariant").val("");
                // Select newly added variant in dropdown menu
            } else {
                //Notify that variant already exists.
            }
        });

        // buttonDeleteVariant manages the change of the delete-button,
        // to confirm the delete-intent of the user
        function buttonDeleteVariant(event) {
            $(event.currentTarget).next().removeClass("d-none");
            $(event.currentTarget).addClass("d-none");
        }

        // deleteTestStep removes the test step-list element from the GUI
        function buttonDeleteVariantConfirm(event) {
            var pressedButton = $(event.currentTarget);
            var idToDelete = pressedButton.attr("id").slice(15);

            deleteVariant(idToDelete);
            pressedButton.parent().remove();
        }

        function deleteVariant(variant) {
            delete projectVersionData[variant];
            var selector = $('#projectVariantSelect');
            selector.find("option[value='" + variant + "']").remove();
            selector.value = selector.children[0];
            showVersions();
        }


        //Versions

        // Shows the versions of the currently selected variant
        function showVersions() {
            var selectedValue = $("#projectVariantSelect").val();
            selectedVariant = selectedValue;

            if(selectedValue === "none") {
                $('#collapseVersions').collapse('hide');
            } else {
                $('#collapseVersions').collapse('show');
                $("#versionList").empty();
                populateVersions(selectedValue);
            }
        }

        // Adds versions to the list with versions
        function populateVersions(selectedVariantKey) {
            var variant = projectVersionData[selectedVariantKey];
            if (variant.Versions === null){
                variant.Versions = [];
            }
            if (variant.Versions.length > 0) {
                $.each(variant.Versions, function(key,version) {
                    addVersion(version);
                });
            }
        }

        // adds a version to the list with versions
        // Parameter version has type {Name: "VersionXYZ"}
        function addVersion(version) {
            var list = $('#versionList');
            var listElement = ($("<li></li>")
                .attr("class","list-group-item")
                .attr("style","display:flex;")
                .html('<span style="width:50%;">'+version.Name+'</span>'));
            var deleteButton = ($("<button></button>")
                .attr("class","btn btn-danger ml-auto list-line-item btn-sm buttonDeleteVersion")
                .attr("id","del-ver-" + version.Name)
                .attr("type","button")
                .html('<i class="fa fa-trash-o" aria-hidden="true"></i>\n' +
                    '<span class="d-none d-sm-inline"> Delete</span>'));
            deleteButton.click(function (event) { buttonDeleteVersion(event); });
            var versionDeleteConfirmButton = ($("<button></button>")
                .attr("class","btn btn-danger ml-auto d-none list-line-item btn-sm buttonDeleteVersionConfirm")
                .attr("id","delConfirm-ver-" + version.Name)
                .attr("type","button")
                .html('<i class="fa fa-check" aria-hidden="true"></i>\n' +
                    '<span class="d-none d-sm-inline"> Confirm delete</span>'));
            versionDeleteConfirmButton.click(function (event) { buttonDeleteVersionConfirm(event); });
            listElement.append(deleteButton);
            listElement.append(versionDeleteConfirmButton);
            list.append(listElement);
        }

        // buttonDeleteTestStepConfirm manages the change of the delete-button,
        // to confirm the delete-intent of the user
        function buttonDeleteVersion(event) {
            $(event.currentTarget).next().removeClass("d-none");
            $(event.currentTarget).addClass("d-none");
        }

        // deleteTestStep removes the test step-list element from the GUI
        function buttonDeleteVersionConfirm(event) {
            var pressedButton = $(event.currentTarget);
            var idToDelete = pressedButton.attr("id").slice(15);
            deleteVersion(projectVersionData[selectedVariant].Versions, idToDelete);
            pressedButton.parent().remove();
        }

        function deleteVersion(versionList, idToDelete) {
            versionList.forEach(function(ver, index) {
                if (ver.Name === idToDelete) {
                    versionList.splice(index, 1);
                }
            });
        }

        /* Adding a handler for the enter key to add a version*/
        $("#inputProjectVersion").keydown(function(event){
            if(event.keyCode === 13){
                event.preventDefault();
                $("#buttonAddProjectVersion").click();
            }
        });

        /* attach a handler to the add test cases form submit button */
        $("#buttonAddProjectVersion").click(function() {
            var versionKey = $("#inputProjectVersion").val().trim();
            if((versionKey !== "")&&(selectedVariant !== "none")&&!containsVersion({Name:versionKey}, projectVersionData[selectedVariant].Versions)) {
                var versionObject = JSON.parse('{"Name":"'+versionKey+'"}');
                projectVersionData[selectedVariant].Versions.push(versionObject);
                addVersion(versionObject);
                $("#inputProjectVersion").val("")
            } else {
                //Notify that variant already exists.
            }
        });

        /* attach a handler to the add test cases form submit button */
        $("#buttonSaveVariants").click(function(event) {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", urlVersions, true);
            xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

            // send the collected data as JSON
            xhr.send(JSON.stringify(projectVersionData));

            xhr.onloadend = function () {
                if (this.status === 200) {
                    $("#modal-manage-versions").modal('hide');
                } else {
                    console.log(this.response);
                }
            };

            if(Object.keys(projectVersionData).length > 0) {
                $("#somevariants").removeClass("d-none");
                $("#novariant").addClass("d-none");
            } else {
                $("#somevariants").addClass("d-none");
                $("#novariant").removeClass("d-none");
            }
        });



    </script>
</div>
{{end}}