/**
 * 
 * @constructor
 * @param {String} name
 * @param {Array} params
 */
Navigation = function (name, params) {
    this.name = name;
    if (!params) {
        this.paramArray = new Array();
    } else if (Array.isArray(params)) {
        this.paramArray = params;
    }
};

/**
 * 
 * @returns {Boolean}
 */
Navigation.prototype.hasParams = function () {
    return (this.paramArray.length > 0);
};

/**
 * 
 * @returns {Number}
 */
Navigation.prototype.getParamLength = function () {
    return (this.paramArray.length > 0);
};

/**
 * 
 * @param {Number} index
 * @returns {String}
 */
Navigation.prototype.getParam = function (index) {
    if (index >= this.paramArray.length) {
        return null;
    }
    return this.paramArray[index];
};

/**
 * 
 * @param {String} paramKey
 * @returns {String}
 */
Navigation.prototype.getParamValue = function (paramKey) {
    var suffix = paramKey + ":";
    for(let param of this.paramArray) {
        if (param.indexOf(suffix) === 0) {
            return param.substring(suffix.length);
        }
    }
    return null;
};

/**
 * 
 * @param {String} fragment
 * @returns {Navigation}
 */
Navigation.parse = function(fragment) {
    if ((!fragment) || (fragment.length === 0)) {
        return null;
    }
    if (fragment.startsWith("#")) {
        fragment = fragment.substring(1);
        if (fragment.length === 0) {
            return null;
        }
    }
    var tokens = fragment.split('|');
    var name = tokens[0];
    var length = tokens.length;
    if (length > 1) {
        let paramArray = new Array();
        for(let i = 1; i < length; i++) {
            let token = tokens[i].trim();
            if (token.length > 0) {
                paramArray.push(token);
            }
        }
        return new Navigation(name, paramArray);
    } else {
        return new Navigation(name);
    }
};

/**
 * 
 * @param {Navigation|String} defaultNavigation
 * @returns {Navigation}
 */
Navigation.getCurrent = function (defaultNavigation) {
    if ((window.location.hash) && (window.location.hash.length > 1)){
        return Navigation.parse(window.location.hash);
    } else if (defaultNavigation instanceof Navigation) {
        return defaultNavigation;
    } else {
        return Navigation.parse("#" + defaultNavigation);
    }
};

Navigation.selectListener = function () {
    if (this.options) {
        var name = this.options[this.selectedIndex].value;
        window.location.hash = "#" + name;
    }
};

/**
 * 
 * @param {Navigation|String} defaultNavigation
 * @param {Function} navigationCallback
 * @returns {undefined}
 */
Navigation.onChange = function (defaultNavigation, navigationCallback) {
    window.onhashchange = function (event) {
        navigationCallback(Navigation.getCurrent(defaultNavigation));
    };	
};
