/**
 * Create a new URL resolver.
 * @function loader.newUrlResolver
 * @param {object} config - Configuration object.
 * @param {object} config.params - Parameters to append.
 * @param {string} [config.basedir='/'] - Context path.
 * @param {string} [config.jsDir='js'] - Javascript directory name.
 * @param {string} [config.cssDir='css'] - Stylesheet directory name.
 * @param {string} [config.imgDir='img'] - Image directory name.
 * @author Taka Okunishi
 *
 */

var url = require('url'),
    appendQuery = require('./append_query');
exports = module.exports = function (config) {
    var ensureDir = exports._ensureDir;
    var baseDir = config.basedir || config.baseDir || '/',
        params = config.params,
        jsDir = ensureDir(config.jsDir || 'js'),
        cssDir = ensureDir(config.cssDir || 'css'),
        imgDir = ensureDir(config.imgDir || 'img'),
        convertRules = config.convertRules || [];

    function convert(filename) {
        var pathAndQuery = filename.split('?');
        var converted = pathAndQuery.shift(),
            queryString = pathAndQuery.pop();
        for (var i = 0, len = convertRules.length; i < len; i++) {
            converted = converted.replace.apply(converted, convertRules[i]);
        }
        if (queryString) {
            converted = [converted, queryString].join('?');
        }
        return converted;
    }

    function resolve(pathname) {
        if (arguments.length > 1) {
            pathname = url.resolve.apply(url, arguments);
        }
        var resolved = url.resolve('/', [baseDir, (pathname || '')].join('/')).replace(/\/\/+/g, '/');
        if (params) {
            resolved = appendQuery(resolved, params);
        }
        return convert(resolved);
    }

    resolve.js = function (pathname) {
        return resolve(jsDir, pathname)
    };
    resolve.css = function (pathname) {
        return resolve(cssDir, pathname);
    };
    resolve.img = function (pathname) {
        return resolve(imgDir, pathname)
    };
    return resolve;
};

exports._ensureDir = function (dirpath) {
    if (!dirpath.match(/\/$/)) {
        return dirpath + '/';
    }
    return dirpath;
};

