{{/*
This file is part of SystemTestPortal.
Copyright (C) 2017  Institute of Software Technology, University of Stuttgart

SystemTestPortal is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SystemTestPortal is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with SystemTestPortal.  If not, see <http://www.gnu.org/licenses/>.
*/}}

{{define "tab-content"}}
{{$parent := .}}
<div class="modal fade" id="deleteModal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-trash"></i> Delete Test Case</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Do you really want to delete the test case? This is irreversible!</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" id="buttonDeleteConfirmed">Delete</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="revertModal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-undo"></i> Revert Test Case</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Do you really want to revert the test case to this version?</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="buttonRevertConfirmed">Revert</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="duplicateModal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa fa-clone"></i> Name Test Case Duplicate</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>This duplicates the current test case up to the currently shown version.
                    The test case duplicate needs a unique name.</p>
                <input class="form-control" id="inputDuplicateTestCaseName"
                       placeholder="Enter name for test case duplicate" required>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="buttonDuplicateConfirmed">Duplicate</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="helpModal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Test Case Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <table class="help-table">
                    <tr>
                        <td colspan="2">
                            This shows the details of a test case.
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2"><h5>Buttons</h5></td>
                    </tr>
                    <tr>
                        <td>
                            <button class="btn btn-secondary">
                                <i class="fa fa-long-arrow-left" aria-hidden="true"></i>
                                <span class="d-none d-sm-inline"> Back</span>
                            </button>
                        </td>
                        <td>Get back to the test case list.</td>
                    </tr>
                {{ if .ProjectPermissions.DeleteCase }}
                    <tr>
                        <td>
                            <button class="btn btn-danger" >
                                <i class="fa fa-trash-o" aria-hidden="true"></i>
                                <span class="d-none d-sm-inline"> Delete</span>
                            </button>
                        </td>
                        <td>Open a confirm dialog before deleting the current test case.</td>
                    </tr>
                {{ end }}
                {{ if .ProjectPermissions.DuplicateCase }}
                    <tr>
                        <td>
                            <button class="btn btn-primary"  formaction="duplicate">
                                <i class="fa fa-clone" aria-hidden="true"></i>
                                <span class="d-none d-sm-inline"> Duplicate</span>
                            </button>
                        </td>
                        <td>Duplicate the test case with history up to the currently selected version.</td>
                    </tr>
                {{ end }}
                    <tr>
                        <td>
                            <button class="btn btn-primary" formaction="history">
                                <i class="fa fa-history" aria-hidden="true"></i>
                                <span class="d-none d-sm-inline"> History</span>
                            </button>
                        </td>
                        <td>Show a list with all previous versions of this test case.</td>
                    </tr>
                {{ if .ProjectPermissions.EditCase }}
                    <tr>
                        <td>
                            <button class="btn btn-primary" formaction="revert">
                                <abbr title="Reverts the test case to the selected version">
                                    <i class="fa fa-undo" aria-hidden="true"></i>
                                    <span class="d-none d-sm-inline">Revert</span>
                                </abbr>
                            </button>
                        </td>
                        <td>Revert the test case to the selected version.</td>
                    </tr>
                    <tr>
                        <td>
                            <button class="btn btn-primary" formaction="edit">
                                <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                                <span class="d-none d-sm-inline"> Edit</span>
                            </button>
                        </td>
                        <td>Edit the current test case.</td>
                    </tr>
                {{ end }}
                {{ if .ProjectPermissions.AssignCase }}
                    <tr>
                        <td>
                            <button class="btn btn-primary" disabled>
                                <i class="fa fa-user-plus" aria-hidden="true"></i>
                                <span class="d-none d-sm-inline"> Assign</span>
                            </button>
                        </td>
                        <td>Assign this test case as a task to a team member.</td>
                    </tr>
                {{ end }}
                {{ if .ProjectPermissions.Execute }}
                    <tr>
                        <td>
                            <button class="btn btn-success">
                                <i class="fa fa-play" aria-hidden="true"></i>
                                <span class="d-none d-sm-inline"> Start</span>
                            </button>
                        </td>
                        <td>Start the execution of the current test case.</td>
                    </tr>
                {{ end }}
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
{{ template "modal-tester-assignment" . }}
<div class="tab-card card" id="tabTestCases">
    <nav class="navbar navbar-light action-bar p-3">
    <div class="input-group flex-nowrap">
        <button class="btn btn-secondary mr-2" id="buttonBack">
            <i class="fa fa-long-arrow-left" aria-hidden="true"></i>
            <span class="d-none d-md-inline"> Back</span>
        </button>
    {{ if .ProjectPermissions.DeleteCase }}
        <button class="btn btn-danger mr-2" id="buttonDelete" data-toggle="modal"
                data-target="#deleteModal">
            <i class="fa fa-trash-o" aria-hidden="true"></i>
            <span class="d-none d-md-inline"> Delete</span>
        </button>
    {{ end }}
    {{ if .ProjectPermissions.DuplicateCase }}
        <button class="btn btn-primary mr-2" id="buttonDuplicate" formaction="duplicate"
                data-toggle="modal" data-target="#duplicateModal">
            <i class="fa fa-clone" aria-hidden="true"></i>
            <span class="d-none d-md-inline"> Duplicate</span>
        </button>
    {{ end }}
        <button class="btn btn-primary mr-2" id="buttonHistory" formaction="history">
            <i class="fa fa-history" aria-hidden="true"></i>
            <span class="d-none d-md-inline"> History</span>
        </button>
    {{ if .ProjectPermissions.EditCase }}
        {{ if ne .TestCaseVersion.VersionNr (index .TestCase.TestCaseVersions 0).VersionNr }}
        <button class="btn btn-primary mr-2" id="buttonRevert" formaction="revert" data-toggle="modal"
                data-target="#revertModal">
            <abbr title="Reverts the test case to the selected version">
                <i class="fa fa-undo" aria-hidden="true"></i>
                <span class="d-none d-md-inline">Revert</span>
            </abbr>
        </button>
         {{ else }}
        <button class="btn btn-primary mr-2" id="buttonEdit" formaction="edit">
            <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
            <span class="d-none d-md-inline"> Edit</span>
        </button>
         {{ end }}
    {{ end }}
    {{ if .ProjectPermissions.AssignCase }}
        <button class="btn btn-primary mr-2" id="buttonAssign" formaction="assign" data-toggle="modal"
                data-target="#modal-tester-assignment">
            <i class="fa fa-user-plus" aria-hidden="true"></i>
            <span class="d-none d-md-inline"> Assign</span>
        </button>
    {{ end }}
    {{ if .ProjectPermissions.Execute }}
        {{ with .TestCaseVersion }}
        {{ if .Steps }}
        <button class="btn btn-success" id="buttonExecute">
        {{ else }}
        <button class="btn btn-success" id="buttonExecute" disabled data-toggle="tooltip" data-placement="bottom"
                title="" data-original-title="This test case has no steps!">
        {{ end }}
            <i class="fa fa-play" aria-hidden="true"></i>
            <span class="d-none d-md-inline"> Start</span>
        </button>
         {{ end }}
    {{ end }}
    </div>
</nav>
    <div class="row tab-side-bar-row">
        <div class="col-md-9 p-3">
            {{ if ne .TestCaseVersion.VersionNr (index .TestCase.TestCaseVersions 0).VersionNr }}
            <div class="alert alert-warning alert-dismissible">
                <a class="close" data-dismiss="alert" aria-label="close">&times;</a>
                <strong>Warning!</strong> You are viewing an older version of the test case
            </div>
            {{ end }}
            <h4 class="mb-3">{{ .TestCase.Name }}</h4>
            {{ with .TestCaseVersion }}
            <div class="form-group">
                <label><strong>Test Case Description</strong></label>
                <p class="text-muted">
                    {{ with .Description }}
                    {{ . }}
                    {{ else }}
                    No Description
                    {{ end }}
                </p>
            </div>
            <div class="form-group">
                <label><strong>Test Case Preconditions</strong></label>
                <p class="text-muted">
                    {{ with .Preconditions }}
                    {{ . }}
                    {{ else }}
                    No Conditions
                    {{ end }}
                </p>
            </div>
            <div class="form-group">
                <label><strong>Test Steps</strong></label>
                {{ if .Steps }}
                <ol class="list-group" id="testStepsAccordion" data-children=".li">
                    {{ range $index, $element := .Steps }}
                    <li class="list-group-item">
                        <a data-toggle="collapse" data-parent="#testStepsAccordion" href="#testStepsAccordion{{ $index }}"
                           aria-expanded="true" aria-controls="testStepsAccordion{{ $index }}">
                            {{ .Action }}
                        </a>
                        <div id="testStepsAccordion{{ $index }}" class="collapse" role="tabpanel">
                            <p class="mb-3">
                                {{ .ExpectedResult }}
                            </p>
                        </div>
                    </li>
                    {{ end }}
                </ol>
                {{ else }}
                <p class="text-muted">No Test Steps</p>
                {{ end }}
            </div>
            {{template "comments" $parent}}
        </div>
        <div class="col-md-3 p-3 tab-side-bar">
            <div class="form-group">
                <label><strong>Applicability</strong></label>
                {{ if .Variants}}
                <div class="form-group">
                    <div class="col-2 col-sm-1 col-md-12 col-lg-12">
                        <label for="inputTestCaseSUTVariants">
                            <strong>Variants</strong>
                        </label>
                    </div>
                    <div class="col-10 col-sm-11 col-md-12 col-lg-12">
                        <select class="custom-select mb-2" id="inputTestCaseSUTVariants"></select>
                    </div>
                    <div class="col-2 col-sm-1 col-md-12 col-lg-12">
                        <label for="inputTestCaseSUTVersions">
                            <strong>Versions</strong>
                        </label>
                    </div>
                    <div class="form-group col-10 col-sm-11 col-md-12 col-lg-12">
                        <ul class="form-control" id="inputTestCaseSUTVersions">
                        </ul>
                    </div>
                </div>
                {{ else }}
                <div class="form-group">
                    <p class="text-muted">This test case is not applicable to any system-under-test versions</p>
                </div>
                {{ end }}
            </div>
            <div class="form-group">
                <label><strong>Estimated Test Duration</strong></label>
                <p class="text-muted">
                    {{ if and (eq $.DurationHours 0) (eq $.DurationMin 0) }}
                    No Test Duration
                    {{ else }}
                    {{ if gt $.DurationHours 0 }}
                    {{ $.DurationHours }}
                    {{ if eq $.DurationHours 1 }} Hour {{ else }} Hours {{ end }}
                    {{ end }}
                    {{ if gt $.DurationMin 0 }}
                    {{ $.DurationMin }}
                    {{ if eq $.DurationMin 1 }}
                    Minute
                    {{ else }}
                    Minutes
                    {{ end }}
                    {{ end }}
                    {{ end }}
                </p>
            </div>
            <div class="form-group">
                <label><strong>Number of Test Steps</strong></label>
                <p class="text-muted">
                    {{ len .Steps }}
                </p>
            </div>
            {{ end }}
            {{ $projectLabels := .Project.Labels }}
            {{ with .TestCase }}
            <div class="form-group">
                <label><strong>Labels</strong></label>
                <select id="btnEditLabels" class="btn-link" multiple="multiple">
                {{ range $indexProject, $labelProject := $projectLabels }}
                    <option value="{{ $indexProject }}">{{ $labelProject.Name }}</option>
                {{ end }}
                </select>
                <p id="labelContainer">
                    {{ range .Labels }}
                    <span class="badge badge-primary">{{ .Name }}</span>
                    {{ else }}
                    <span class="text-muted">No Labels</span>
                    {{ end }}
                </p>
            </div>
            {{ end }}
            {{ with .TestCaseVersion }}
            <div class="form-group">
                <label><strong>Tester</strong></label>
                <p id="testerContainer">
                {{ range .Tester }}
                    <span class="badge badge-primary">
                    {{ .DisplayName}}
                    </span>
                {{ else }}
                    <span class="text-muted">No assigned testers</span>
                {{ end }}
                </p>
            </div>
            {{ end }}
        </div>
    </div>
    <script src="/static/js/util/common.js"></script>
    <script src="/static/js/project/testcases.js"></script>
    <script src="/static/js/project/sut-versions-show.js"></script>
    <script>
        assignButtonsTestCase();
        // Listen to changes in the drop down menu of the variants
        setVariantOnChangeListener();


        // SUT VARIANTS AND VERSIONS

        // Send a request to get the sut variants and versions
        var url = currentURL();

        // If the newID variable is not yet defined
        // use the test-case-id from the url.
        // Else use the saved name. The name of a test-case
        // needs to be saved because after editing the
        // name of a test case, the url still contains the
        // old name of the test case and the request
        // for the sut-versions would be sent to the wrong url
        if (!newID || newID !== {{ .TestCase.ID.Test }}) {
            newID = url.segments[4];
        }

        // Request test case to get the sut versions from it
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url.takeFirstSegments(4).appendSegment(newID).appendSegment("json").toString(), true);
        xmlhttp.send();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
                testcase = JSON.parse(this.responseText);
                testCaseVersionIndex = (testcase.TestCaseVersions).length - {{ .TestCaseVersion.VersionNr }};
                testObjectVersionData = testcase.TestCaseVersions[testCaseVersionIndex].Variants;

                // Fill the drop down menu with the variants
                fillVariants(testObjectVersionData, "#inputTestCaseSUTVariants");
                // Update the version list with the versions of the selected variant
                updateVersionShowList();
            }
        };

        // BUTTON HANDLERS
        // Handler for the revert button of older test case versions
        $("#buttonRevertConfirmed").click(function () {

            $('#revertModal').on('hidden.bs.modal', function (e) {
                e.preventDefault();

                /* Send the data using post with element ids*/
                var posting = $.ajax({
                    url: currentURL().appendSegment("update").toString() + "?fragment=true",
                    type: "PUT",
                    data: {
                        version: "{{ .TestCaseVersion.VersionNr }}",
                        inputCommitMessage: "Revert test case to version {{ .TestCaseVersion.VersionNr }}",
                        inputTestCaseName: "{{ .TestCase.Name }}",
                        inputTestCaseDescription: "{{ .TestCaseVersion.Description }}",
                        inputTestCasePreconditions: "{{ .TestCaseVersion.Preconditions }}",
                        inputHours: "{{ .DurationHours }}",
                        inputMinutes: "{{ .DurationMin }}"
                    }
                });

                /* Alerts the results */
                posting.done(function (response) {
                    var url = currentURL()
                        .takeFirstSegments(4)
                        .appendCodedSegment(posting.getResponseHeader("newName"))
                        .toString();

                    $('#tabarea').empty().append(response);
                    history.pushState('data', '', url);
                }).fail(function (response) {
                    $("#modalPlaceholder").empty().append(response.responseText);
                    $('#errorModal').modal('show');
                });
            }).modal('hide');
        });

        $('#buttonDuplicateConfirmed').off('click').click(function() {

            $('#duplicateModal').off('click').one('hidden.bs.modal', function (e) {
                e.preventDefault();

                var url = currentURL().appendSegment("duplicate").toString() + "?fragment=true";

                var posting = $.post(url, {
                    inputTestCaseName: $('#inputDuplicateTestCaseName').val(),
                    version: "{{ .TestCaseVersion.VersionNr }}"
                });

                posting.done(function (r) {
                    url = currentURL()
                        .takeFirstSegments(4)
                        .appendCodedSegment(posting.getResponseHeader("newName"))
                        .toString();

                    $('#tabTestCases').empty().append(r);
                    history.pushState('data', '', url);
                }).fail(function (r) {
                    $("#modalPlaceholder").empty().append(r.responseText);
                    $('#errorModal').modal('show');
                });
            }).modal('hide');
        });


        $("#printerIcon").removeClass("d-none");

        function printer() {
            window.open(currentURL().appendSegment("print").toString(),
                    'newwindow',
                    'width=600,height=800');
            return false;
        }
    </script>

    <script src="/static/js/project/labels.js"></script>
    <!-- Include the plugin's CSS and JS: -->
    <script type="text/javascript" src="/static/libraries/bootstrap-multiselect/js/bootstrap-multiselect.js"></script>
    <link rel="stylesheet" href="/static/libraries/bootstrap-multiselect/css/bootstrap-multiselect.css" type="text/css"/>
    <!-- Initialize bootstrap-multiselect-->
    <script type="text/javascript">

        // testCaseLabels is an array with all the labels of the test case
        var testCaseLabels = {{ .TestCase.Labels }};
        if (testCaseLabels === null) {
            testCaseLabels = [];
        }

        // Save the labels of project
        // It's needed to reference the correct label when changing the
        // labels of the test case
        var projectLabels = {{ .Project.Labels }};

        $(document).ready(function() {
            var btnEditLabels = $('#btnEditLabels');

            btnEditLabels.multiselect({
                buttonClass: 'btn btn-link',
                buttonText: function(options, select) {
                    return 'Edit';
                },
                // Send request to server to update labels of test case
                onDropdownHide: function(event) {
                    // The url to send the update request to
                    var urlLabelsPost = getTestURL().appendSegment("labels").toString();

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

                    // Clear the array with the old labels of the test case
                    testCaseLabels.length = 0;
                    // Save the newly selected labels in the array with labels
                    btnEditLabels.val().forEach(function(labelIndex) {
                        testCaseLabels.push(projectLabels[labelIndex])
                    });

                    // Send the array of labels as JSON to the server
                    xhr.send(JSON.stringify(testCaseLabels));

                    xhr.onloadend = function () {
                        if (this.status !== 200) {
                            console.log(this.response);
                        }
                    };
                    // Update labels of test case in gui
                    showLabels(testCaseLabels, "#labelContainer");
                }
            });
            btnEditLabels.multiselect('select', getIndexOfTestCaseLabels());
        });

        // getIndexOfTestCaseLabels returns the indices of the
        // labels of the test case. These labels are selected in
        // the labels-dropdown.
        function getIndexOfTestCaseLabels() {
            var indexList = [];
            testCaseLabels.forEach(function(testCaseLabel) {
                projectLabels.forEach(function(projectLabel, projectLabelIndex) {
                   if (testCaseLabel.Name === projectLabel.Name) {
                       indexList.push(projectLabelIndex);
                   }
                });
            });
            return indexList;
        }
    </script>

</div>
{{ end }}