var fs = require('fs');

function Url(url) {
    this.url = url;
    if (this.url.indexOf('?') >= 0)
        this.url = this.url.substr(0, this.url.indexOf('?'));
    while (this.url.length && this.url[0] === '/') {
        this.url = this.url.substr(1);
    }
    urlParts = this.url.split("/");
    this.urlParts = [];
    for (var i =0, nbParts = urlParts.length; i < nbParts; i++) {
        if (urlParts[i])
            this.urlParts.push(urlParts[i]);
    }
    var stop = url.indexOf("?");
    if (stop === -1) {
        stop = url.length;
    }
    this.path = url.substr(0, stop);
    var queryTokens = url.substr(stop +1).split("&");
    this.queryTokens = {};
    for (var i =0, nbTokens = queryTokens.length; i < nbTokens; i++) {
        var token = queryTokens[i].split("=");
        if (token[0] !== "") {
            if (!this.queryTokens[token[0]]) {
                this.queryTokens[token[0]] = [];
            }
            this.queryTokens[token[0]].push(token[1] || true);
        }
    }
    this.serve = null;
    try{
        if (!this.urlParts.length) {
            this.serve = {
                filename: "public/index.html"
                ,stat: fs.statSync("public/index.html")
            };
        } else if (this.urlParts.length == 1) {
            this.serve = {
                filename: "public/" +this.urlParts[0]
                ,stat: fs.statSync("public/" +this.urlParts[0])
            };
        }
    } catch (e) {
        // Not a public/ file
    }
}

Url.prototype.isPublic = function() {
    return this.serve !== null;
};

Url.prototype.getReadStream = function() {
    return fs.createReadStream(this.serve.filename);
};

Url.prototype.match = function(arr) {
    if (arr.length !== this.urlParts.length)
        return false;
    for (var i=0, arrLen = arr.length; i < arrLen; i++)
        if (arr[i] !== this.urlParts[i] && arr[i] !== '?')
            return false;
    return true;
}

module.exports = { Url: Url };

