/*
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 getOwnerURL() {
    return currentURL().takeFirstSegments(2);
}
function getProjectURL() {
    return currentURL().takeFirstSegments(3);
}
function getTestURL() {
    return currentURL().takeFirstSegments(5);
}
function getProjectTabURL() {
    return currentURL().takeFirstSegments(4);
}

//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 URL(string.substring(0,l-1).split("/"));
    }
    else{
        return new URL(string.split("/"));
    }
}

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;
}

function URL(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) {
        var copy = new URL(this.segments);
        copy.segments = copy.segments.slice(0, this.segments.length - n);
        return copy;
    };
    this.takeFirstSegments = function(n) {
        var copy = new URL(this.segments);
        copy.segments = copy.segments.slice(0, n);
        return copy;
    };
    this.appendSegment = function(s) {
        var copy = new URL(this.segments);
        copy.segments.push(s);
        return copy;
    };
    this.appendCodedSegment = function(s) {
        var decoded = decodeURIComponent(s);
        return this.appendSegment(decoded);
    };
}