/*
 * Copyright (c) 2012-2015 Kaarle Ritvanen
 * See LICENSE file for license details
 */

angular.module("aconf").factory("aconfPath", function() {
    function split(path) {
	var res = [];
	var comp = "";
	var escaped;

	function merge(s) {
	    var n = Number(s);
	    if (s > "") res.push((escaped || isNaN(n)) ? s : n);
	}

	while (true) {
	    var m = path.match(/^([^\\\/]*)([\\\/])(.*)/);
	    if (!m) {
		merge(comp + path);
		return res;
	    }

	    comp += m[1];
	    if (m[2] == "\\") {
		comp += m[3].substring(0, 1);
		escaped = true;
		path = m[3].substring(1);
	    }
	    else {
		merge(comp);
		comp = "";
		escaped = false;
		path = m[3];
	    }
	}
    }

    function escape(name) {
	if (!_.isString(name)) return String(name);
	name = name.replace(/([\\\/])/g, "\\$1");
	if (isNaN(Number(name))) return name;
	return "\\" + name;
    }

    function join() {
	var arg = _.toArray(arguments);
	if (arg.length == 1) return arg[0];

	var path = arg.shift();
	var name = arg.shift();

	arg.unshift((path == "/" ? "" : path) + "/" + escape(name));

	return join.apply(undefined, arg);
    }

    return {
	split: split,
	join: join,
	isSubordinate: function(p1, p2, real) {
	    p1 = split(p1);
	    p2 = split(p2);
	    if (real && p1.length <= p2.length) return false;
	    for (var i = 0; i < p2.length; i++)
		if (p1[i] != p2[i]) return false;
	    return true;
	}
    };
});
