{{define "modal-manage-labels"}}
{{$maxNameLength:=50}}

<!-- Label-Modal -->
<div class="modal fade" id="modal-manage-labels" tabindex="-1" role="dialog" aria-labelledby="modal-manage-labels-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-labels-label"><i class="fa fa-wrench" aria-hidden="true"></i> Manage Labels</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" style="border-bottom: 1px solid #e9ecef;">
                <h5>New Label</h5>
                <div class="row">
                    <div class="col-12">

                        <div class="input-group mb-3">
                            <span class="input-group-addon" id="label-name-label">Name</span>
                            <input type="text" class="form-control" id="inputProjectLabelName" placeholder="e.g. GUI" aria-label="e.g. GUI" aria-describedby="label-name-label" maxlength="{{$maxNameLength}}">
                        </div>
                        <div class="input-group mb-3">
                            <span class="input-group-addon" id="label-description-label">Description</span>
                            <input type="text" class="form-control" id="inputProjectLabelDescription" placeholder="e.g. Tests for the Graphical User Interface" aria-label="e.g. Tests for the Graphical User Interface" aria-describedby="label-description-label">
                        </div>
                        <div class="input-group mb-3">
                            <span class="input-group-addon" id="label-color-label">Color</span>
                            <div class="color-selector-box form-control">
                                {{range .LabelColors}}
                                    <span class="color-selector clickIcon" id="{{ . }}" style="background-color: #{{ . }};"></span>
                                {{end}}
                            </div>
                        </div>
                        <div class="input-group mb-3">
                            <span class="input-group-addon" id="label-preview-label">Preview</span>
                            <div class="color-selector-box form-control">
                                <span id="preview-label" class="badge badge-primary" style="background-color: #007bff;">Preview</span>
                            </div>
                        </div>

                        <button id="buttonAddProjectLabel" class="btn btn-secondary float-right" type="button">Add</button>
                    </div>
                </div>
            </div>
            <div class="modal-body">
                <h5>Labels</h5>
                <div class="row">
                    <div class="col-12">
                        <p id="projectLabelList">

                        </p>
                    </div>
                </div>
                <br>
            </div>
            <div class="modal-footer">
                <button id="buttonSaveLabels" 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();
        // projectLabelData contains the labels of a project
        var projectLabelData = {};

        var urlLabels = getProjectURL().appendSegment("labels").toString();

        xmlhttp.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
                projectLabelData = JSON.parse(this.responseText);
                if (projectLabelData === null) {
                 projectLabelData = [];
                }
                fillLabels(projectLabelData, "#projectLabelList");
            }
        };
        xmlhttp.open("GET", urlLabels, true);
        xmlhttp.send();

        // fillLabels gets a map with labels and adds them to the list with the selectorID
        function fillLabels(labelMap, selectorID) {
            $(selectorID).empty();
            $.each(labelMap, function(key,label) {
                addLabel(label, selectorID);
            });
        }

        // addLabel adds a label to the list
        function addLabel(label, selectorID) {
            var selector = $(selectorID);
            selector.append($("<span></span>")
                    .attr("id", "label-" + label.Name)
                    .attr("class", "badge badge-primary")
                    .attr("data-toggle", "tooltip")
                    .attr("data-placement", "bottom")
                    .attr("data-original-title", label.Description)
                    .attr("style", "background-color:#" + label.Color + ";")
                    .html(label.Name+"&nbsp;<strong><span class=\"closeX\" onClick=\"removeLabel('"+label.Name+"')\" aria-hidden=\"true\">&times;</span></strong>"));
        }

        /* Handler for enter-key*/
        $("#inputProjectLabelName").keydown(function(event){
            if(event.keyCode === 13){
                event.preventDefault();
                $("#inputProjectLabelDescription").focus();
            }
        });
        $("#inputProjectLabelName").keyup(function(event){
            updatePreview("name", $("#inputProjectLabelName").val().trim());
            if($("#inputProjectLabelName").val().trim() == "") {
                updatePreview("name", "Preview");
            }
        });

        $("#inputProjectLabelDescription").keydown(function(event){
            if(event.keyCode === 13){
                event.preventDefault();
                $("#buttonAddProjectLabel").click();
            }
        });

        {{range .LabelColors}}
            $("#{{ . }}").click(function(event) {updatePreview("color", "{{ . }}")});
        {{end}}

        function updatePreview(attr, val) {
            if (attr == "name") {
                if (val == "") {
                    val = $("#inputProjectLabelName").val().trim();
                }
                $("#preview-label").html(val);
            } else if (attr == "color") {
                $("#preview-label").attr("style","background-color: #" + val + ";");
            } else {

            }
        }


        /* attach a handler to the add button */
        $("#buttonAddProjectLabel").click(function(event) {
            var labelName = $("#inputProjectLabelName").val().trim();
            var labelDesc = $("#inputProjectLabelDescription").val().trim();
            var labelColor = $("#preview-label").attr("style");
            labelColor = labelColor.substring(19, 25);
            if((labelName !== "") && (labelName.length <= {{$maxNameLength}}) && !containsLabel(projectLabelData, labelName)) {
                projectLabelData.push(JSON.parse('{"Name":"'+labelName+'","Description":"'+labelDesc+'","Color":"'+labelColor+'"}'));
                addLabel({Name:labelName,Description:labelDesc,Color:labelColor}, "#projectLabelList");
                // Clear text field
                $("#inputProjectLabelName").val("");
                $("#inputProjectLabelDescription").val("");

                //Reset Preview Label
                updatePreview("name", "Preview");
                updatePreview("color", "007bff");

                // Select newly added label in dropdown menu
            } else {
                //Notify that label already exists.
            }

            var tips = $('[data-toggle="tooltip"]');
            if(tips != null)
            {
                tips.tooltip({
                    trigger : 'hover'
                });
            }
        });

        // containsLabel checks whether the list of project labels
        // already contains a label with the labelName
        // Returns true if the list contains a label, else return false
        function containsLabel(projectLabels, labelName) {
            var contains = false;
            projectLabels.forEach(function(projectLabel) {
               if (projectLabel.Name === labelName) {
                   contains = true;
               }
            });
            return contains;
        }

        // removeLabel removes a label from the GUI
        function removeLabel(name) {
            $(".tooltip").hide();
            var elem = document.getElementById("label-" + name);
            elem.parentNode.removeChild(elem);
            deleteLabel(name, projectLabelData);
            return false;
        }

        // deleteLabel deletes a label with the given name from the given list.
        // It is called by the removeLabel() function
        function deleteLabel(name, list) {
            list.forEach(function(value, index) {
                if (value.Name === name) {
                    list.splice(index, 1)
                }
            });
            return list;
        }

        /* attach a handler to the add test cases form submit button */
        $("#buttonSaveLabels").click(function(event) {
            var urlLabelsPost = getProjectURL().appendSegment("labels").toString();

            var xhr = new XMLHttpRequest();
            xhr.open("POST", urlLabelsPost, true);
            xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

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

            xhr.onloadend = function () {
                if (this.status === 200) {
                    $("#modal-manage-labels").modal('hide');

                    // Update labels of test case in gui
                    showLabels(projectLabelData, "#labelContainer");
                    location.reload();
                } else {
                    console.log(this.response);
                }
            };
        });
    </script>
</div>
{{end}}