/*
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/>.
*/

$.getScript("/static/js/util/common.js");
$.getScript("/static/js/util/ajax.js");

var visibleItemCount;
var badgeFilter;
var offsetCount;
var itemMargin;
var hitMax;

function initDataTree() {
    visibleItemCount = 0;
    badgeFilter = -1;
    offsetCount = 1;
    itemMargin = -2.5;
    hitMax = false;

    if (document.getElementById("timeline-list") != null) {
        DataTree.setVisibleItemsToListLength();
        DataTree.reAdjustTimelineItems();
        DataTree.setItemMargin(itemMargin);
    }
}

var DataTree = class DataTree {
    // USER INVOKED FUNCTIONS ----------------------------------------------------------------------------------------------------------------|
    /**
     * Invoked when user clicks a hotlink to a protocol
     * @param test - The unique test identifier
     * @param protocol - The protocol number
     * @param isSequence - True if sequence, false else
     */
    static onUserClickedProtocol(test, protocol, isSequence) {
        const url = isSequence === true
            ? getProjectURL().appendSegment("protocols").appendSegment("testsequences").appendSegment(test).appendSegment(protocol).toString()
            : getProjectURL().appendSegment("protocols").appendSegment("testcases").appendSegment(test).appendSegment(protocol).toString();

        ajaxRequestFragment(null, url, {protocolNr: protocol}, "GET");
    }

    /**
     * Invoked when user clicks on a hotlink to a test
     * @param test - The unique test identifier
     * @param protocol - The protocol number
     * @param isSequence - True if sequence, false else
     */
    static onUserClickedTest(test, isSequence) {
        const url = isSequence === true
            ? getProjectURL().appendSegment("testsequences").appendSegment(test).toString()
            : getProjectURL().appendSegment("testcases").appendSegment(test).toString();

        ajaxRequestFragment(null, url, "", "GET");
    }

    /**
     * Called when user clicks on a badge
     * @param badgetype
     */
    static onUserClickedBadge(badgeType) {
        // If the clicked badge is the current filter, reset
        if (badgeFilter == badgeType) {

            DataTree.removeFilter();
            badgeFilter = -1

        } else {

            DataTree.filterForBadge(badgeType);
            badgeFilter = badgeType

        }
    }

    /**
     * Called when user clicks on any user name
     * @param userName
     */
    static onUserClickedUserName(userName) {
        url =  currentURL().takeFirstSegments(1).appendSegment("users").appendSegment(userName).toString();
        location.href = url;
    }
    // FILTERIN & COUNTING --------------------------------------------------------------------------------------------------------------|
    /**
     * Filters for a badge and reAdjusts the timeline. CAlles load more items if visible item count is < 20
     * @param badgeType
     */
    static filterForBadge(badgeType) {
        visibleItemCount = 0;

        const list = document.getElementById("timeline-list");
        const listItems = list.getElementsByTagName("li");

        for (let i = 0; i < listItems.length; i++) {
            if (listItems[i].id != badgeType) {
                listItems[i].style.display = "none";
            } else {
                visibleItemCount++;
            }
        }

        //if(visibleItemCount < 20) {
          //  DataTree.loadNewItemLine();
        //}

        DataTree.reAdjustTimelineItems();
    }

    /**
     * Remove the filter and readjust the timeline
     */
    static removeFilter() {
        const list = document.getElementById("timeline-list");
        const listItems = list.getElementsByTagName("li");

        for (var i = 0; i < listItems.length; i++) {
            listItems[i].style.display = "block";
        }

        visibleItemCount = listItems.length;
        DataTree.reAdjustTimelineItems()
    }

    static setVisibleItemsToListLength() {
        const list = document.getElementById("timeline-list");

        const listItems = list.getElementsByTagName("li");

        visibleItemCount = listItems.length;
    }
    // DISPLAY FUNCTIONS ----------------------------------------------------------------------------------------------------------------|

    /**
     * Sets the margin of all timeline items to eachother
     * @param margin
     */
    static setItemMargin(margin) {
        const list = document.getElementById("timeline-list");

        if (list == null) {
            return
        }

        const listItems = list.getElementsByTagName("li");

        for (var i = 0; i < listItems.length; i++) {
            listItems[i].style.marginBottom = margin.toString() + "rem";
        }
    }

    /**
     * Makes timeline items alternate on the timeline
     */
    static reAdjustTimelineItems() {
        const list = document.getElementById("timeline-list");
        const listItems = list.getElementsByTagName("li");

        let isInverted = false;
        for (let i = 0; i < listItems.length; i++) {
            if (isInverted) {
                listItems[i].classList.add('timeline-inverted');
                isInverted = false;
            } else {
                listItems[i].classList.remove('timeline-inverted');
                isInverted = true;
            }
        }
    }

    /**
     * Loads a new line of items from the server
     */
    static loadNewItemLine() {
        if(!hitMax){

            // Show the loader
            $('#loader-timeline').show();

            // Send a request to the server to load the next 20 items
            $.ajax({

                url: `${currentURL().takeFirstSegments(3)}/activity`,
                type: "PUT",
                data: {
                    offsetCount: offsetCount
                }

            }).done(response => {
                // Store the number of visible list items before appending
                let temp = visibleItemCount;

                // ADD THE NEW ROWS AND FORMAT ----------------------------------------------------|
                $('#timeline-list').append(response);

                // Show the timestamps
                $("time.timeago").timeago();

                // If we are currently in filter mode, reapply the filter to the new activities. Otherwise count all items.
                if(badgeFilter != -1) {
                    DataTree.filterForBadge(badgeFilter);
                } else {
                    DataTree.setVisibleItemsToListLength();
                }

                DataTree.setItemMargin(itemMargin);
                DataTree.reAdjustTimelineItems();
                //----------------------------------------------------------------------------------|
                // If the visibleListItems is the same as before appending, load another batch of items
                if (visibleItemCount == temp) {

                    offsetCount++;
                    DataTree.loadNewItemLine();

                } else {

                    // Hide the loading icon
                    $('#loader-timeline').hide();
                    offsetCount++;

                }

            }).fail(response => {

                // Hide the loading icon
                $('#loader-timeline').hide();
                hitMax = true;
            });
        }
    }
}

window.onscroll = function(ev) {
    if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
      DataTree.loadNewItemLine();
    }
};

function updateMargin(){
    var margin = $( "#slider" ).slider( "value" );
    DataTree.setItemMargin(margin);
    itemMargin = margin;
}

// HOTKEYS ---------------------------------------------|
function incrementMargin(){
    var value = $("#slider").slider('value');
    var max = $("#slider").slider('option', 'max');

    if ( value < (max)) {
        $("#slider").slider( "value", value + 0.1 );
    }
}

function decrementMargin() {
    var value = $("#slider").slider("value");
    var min = $("#slider").slider('option', 'min');

    if ( value > min) {
        $("#slider").slider("value", value - 0.1 );
    }
}

$(document).off("keydown.event").on("keydown.event", function (event) {

        if($('.modal .active').length > 0){

            return;

        }                switch (event.target.tagName) {

            case "INPUT": case "SELECT": case "TEXTAREA": return;

        }

        switch (event.key) {
            case "+":
                incrementMargin();

                break;

            case "-":
                decrementMargin();

                break;
        }
});
// --------------------------------------------------------|