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


(function($) {
    // You pass-in jQuery and then alias it with the $-sign
    // So your internal code doesn't change
})(jQuery);

// extracts the base URL for the current owner
function getOwnerURL() {
    return currentURL().takeFirstSegments(2);
}
// extracts the base URL for the current project
function getProjectURL() {
    return currentURL().takeFirstSegments(3);
}
// extracts the base URL for the current test
function getTestURL() {
    return currentURL().takeFirstSegments(5);
}
// extracts the base URL for the current project tab
function getProjectTabURL() {
    return currentURL().takeFirstSegments(4);
}

// converts a String in an interactive field of URL segments
//input string should be an uncoded url path
function urlify(string) {
    var l = string.length;
    var lastChar = string.substring(l-1,l);
    if (lastChar === "/"){
        return new getURL(string.substring(0,l-1).split("/"));
    }
    else{
        return new getURL(string.split("/"));
    }
}

// returns the current URL
function currentURL(){
    var result = urlify(window.location.pathname);

    for (var i = 0; i < result.segments.length; i++){
        result.segments[i] = decodeURIComponent(result.segments[i]);
    }
    return result;
}

// returns the current URL
function buildURL(pathname){
    var result = urlify(pathname);

    for (var i = 0; i < result.segments.length; i++){
        result.segments[i] = decodeURIComponent(result.segments[i]);
    }
    return result;
}

// returns a field with various functions
function getURL(seg) {
    this.segments = seg;
    this.toString = function () {
        var result = [];
        for (i = 0; i < this.segments.length; i++){
            result[i] = encodeURIComponent(this.segments[i]);
        }
        return result.join("/");
    };
    this.removeLastSegments = function(n) {
        const copy = new getURL(this.segments);
        copy.segments = copy.segments.slice(0, this.segments.length - n);
        return copy;
    };
    this.takeFirstSegments = function(n) {
        const copy = new getURL(this.segments);
        copy.segments = copy.segments.slice(0, n);
        return copy;
    };
    this.appendSegment = function(s) {
        const copy = new getURL(this.segments);
        copy.segments.push(...s.toString().split("/"));
        return copy;
    };
    this.appendCodedSegment = function(s) {
        var decoded = decodeURIComponent(s);
        return this.appendSegment(decoded);
    };
}

// Retrieves the previously stored filters in the sessionStorage and returns them in an array
// Returns an empty array if there were no previous filters 
function getFilterFromSession() {
    var filters_string = sessionStorage.getItem("filters");
    var last_project = sessionStorage.getItem("project");

    var filters;
    if (filters_string == null) {
        filters = [];
        sessionStorage.setItem("filters", JSON.stringify(filters));
    } else {
        var filters = JSON.parse(filters_string);
    }

    return filters;
}

// Adds filter to the array filters if filter is not an element of filters
// Removes filter from the array filters if filter is an element of filters
function handleFilterOnFilters(filter, filters) {
    position = $.inArray(filter,filters);
    if ( ~position ) {
        filters.splice(position,1);
    } else {
        filters.push(filter);
    }
    sessionStorage.setItem("filters", JSON.stringify(filters));
    return filters;
}

function clearSelection() {
    if(document.selection && document.selection.empty) {
        document.selection.empty();
    } else if(window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
    }
}

/**
 * Reloads the tooltips of the page.
 */
function reloadTooltips(){
    $('[data-toggle="tooltip"]').tooltip({
        trigger : 'hover'
    });
}

/** http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/ */
String.prototype.hashCode = function(){
    let hash = 0, char;
    if (this.length === 0) return hash;
    for (let i = 0; i < this.length; i++) {
        char = this.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
};

/**
 * This method sends an ajax request to parse the input (raw markdown) into sanitized html
 * @param input The raw markdown string to parse
 * @returns {JQuery.jqXHR}
 */
function sanitize(input) {
    return $.ajax({
        url: currentURL().takeFirstSegments(0) + "/sanitize",
        type: "POST",
        data: {"text": input}

    }).fail(response => {

        $("#modalPlaceholder").empty().append(response.responseText);
        $("#errorModal").modal("show");

    });
}

/**
 * This method sends an ajax request to parse the input (raw markdown) into sanitized html
 * @param input The raw markdown string to parse
 * @returns {JQuery.jqXHR}
 */
function parseMarkdown(input) {
    return $.ajax({
        url: currentURL().takeFirstSegments(0) + "/markdown",
        type: "POST",
        data: {"text": input}

    }).fail(response => {

        $("#modalPlaceholder").empty().append(response.responseText);
        $("#errorModal").modal("show");

    });
}

/**
 * Returns the initial font-size of the html element
 */
var rem = function rem() {
    var html = document.getElementsByTagName('html')[0];

    return function () {
        return parseInt(window.getComputedStyle(html)['fontSize']);
    }
}();

/**
 * Converts pixel to rem
 * @param length The pixels
 * @returns {number} The size in rem
 */
function toRem(length) {
    return (parseInt(length) / rem());
}


/** jQuery document ready:
 * - style all tooltips correctly
 * - Stores the page history
 */
$(function () {

    updateTabs(currentURL().segments[3]);
    reloadTooltips();
    pushHistory();
});
