/**
 * Find up an apeman project.
 * @function apeman.findupProject
 * @param {string} [dirname=process.cwd()] - Directory name to start find up.
 * @returns {object} - An apeman project.
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    fs = require('fs');
/**
 * Find up apeman file.
 * @param {string} dirname - Directory name to start find up.
 * @returns {*}
 * @protected
 */
exports = module.exports = function (dirname) {
    if (!dirname) return null;
    var workingDir = path.resolve(dirname);
    do {
        var apemanfile = exports._findInDir(workingDir);
        if (apemanfile) {
            return apemanfile;
        }
        workingDir = exports._parentDir(workingDir);
    } while (workingDir);
    return null;
};

/**
 * Get parent directory path.
 * @param {string} dirname - Directory name.
 * @returns {string} - Parent directory.
 * @protected
 * @ignore
 */
exports._parentDir = function (dirname) {
    var parentDir = path.dirname(dirname);
    var changed = parentDir != dirname;
    return changed ? parentDir : null;
};

/**
 * Find an apeman file in a directory.
 * @param {string} dirname - Directory name to find.
 * @returns {string|null} - Found file.
 * @protected
 * @ignore
 */
exports._findInDir = function (dirname) {
    var filenames = exports._apemanFileNames;
    for (var i = 0; i < filenames.length; i++) {
        var resolved = path.resolve(dirname, filenames[i]);
        var hit = fs.existsSync(resolved);
        if (hit) {
            return resolved;
        }
    }
    return null;
};

exports._apemanFileNames = [
    'Apemanfile.js',
    'apemanfile.js',
    'Apemanfile.json',
    'apemanfile.json',
    'Apemanfile',
    'apemanfile'
];