/**
 * @file Apeman app configuration file.
 * @namespace apemanfile
 * @param {object} apeman - Apeman module.
 * @returns {object} - An apeman file object.
 * @see {@link http://www.npmjs.org/package/apeman | apeman}
 * @author okuni
 *
 */
var path = require('path');
module.exports = (function (apeman) {
    var cwd = process.cwd();
    process.chdir(__dirname);

    var Apemanfile = apeman.ApemanfileObject,
        prototypePath = apeman.findupApp('apc-static-heir'),
        prototype = require(prototypePath)(apeman),
        basedir = __dirname;


    // Helper modules
    var prototypeHelper = prototype.helper();
    var h = prototypeHelper.fallbackCopy(prototypeHelper, {
        lookupPaths: [basedir].concat(prototypeHelper.lookupPaths),
        scaffoldSettingFilePath: 'settings/scaffold-setting.js'
    });


    // Add helper functions if _apemanfile_helper.js found.
    h.loadLocalHelperFile();

    var meta = {
        name: 'apc-restful',
        version: h.readLocalVERSION() || '0.0.0',
        description: 'Restful app',
        repository: 'https://github.com/apeman-apps/apc-restful',
        author: {
            name: 'Taka Okunishi',
            email: "okunishinishi@apeman.info"
        }
    };


    /**
     * File system structure data.
     * An empty object represent a directory.
     * @type object
     * @private
     */
    var structureData = {
        '_apemanfile_helper.js': h.newApemanfileHelperJsFile(h.apemanHelperData),
        lib: {
            date: {},
            db: {},
            random: {},
            expression: {}
        },
        serverside: {
            database: {},
            model: {}
        },
        settings: {
            'scaffold-setting.js': h.newScaffoldSettingJsFile().force(false).mode('644')
        },
        test: {
            unit_tests: {
                lib: {
                    date: {},
                    db: {},
                    random: {},
                    expression: {}
                },
                serverside: {
                    database: {},
                    model: {}
                }
            },
            data: {
                expanded: {},
                seeds: {},
                patterns: {}
            }
        },
        tmpl: {
            js: {
                settings: {}
            }
        },
        '.gitignore': {
            _data: {
                patterns: [
                    ".coveralls.yml",
                    ".apemanhelperdata",
                    "settings/secrets/*-secret.js",
                    "test/data/expanded/*-expanded.js"
                ]
            }
        }
    };

    /**
     * Packages installed by npm.
     * @type object
     * @private
     */
    var nodePackages = {
        'sqlite3': '~2.2.0',
        "mongojs": "~0.10.0",
        "pluralize": "~0.0.6",
        "express": "~3.4.8",
        "validator": "~3.1.0"
    };

    /**
     * Packages installed by npm for development user.
     * @type {object}
     * @private
     */
    var nodePackages$dev = {

    };

    var prototypeTasks = prototype.tasks();

    var baseConstants = {

        },
        productionConstants = h.fallbackCopy(baseConstants, {

        }),
        devConstants = h.fallbackCopy(baseConstants, {

        }),
        scenarioTestConstants = h.fallbackCopy(baseConstants, {

        }),
        browserScenarioTestConstants = h.fallbackCopy(baseConstants, {

        }),
        docConstants = h.fallbackCopy(baseConstants, {

        }),
        ciConstants = h.fallbackCopy(baseConstants, {

        }),
        operationConstants = h.fallbackCopy(baseConstants, {

        }),
        operationDevConstants = h.fallbackCopy(operationConstants, {

        });


    var tasks = {
        structure: {
            config: {
                data: structureData
            }
        },
        build: prototypeTasks.build.concat([

        ]),
        index: prototypeTasks.index.concat([

        ]),
        expandDataSeed: h.expandDataSeedFilesTask({
            srcDir: 'test/data/seeds',
            destDir: 'test/data/expanded',
            patternFiles: {
                ja: 'test/data/patterns/ja/*.json',
                en: 'test/data/patterns/en/*.json'
            }
        }),
        testData: [
            'expandDataSeed'
        ],
        installNodePackages: {
            config: {
                packages: nodePackages
            }
        },
        installNodeDevPackages: {
            config: {
                packages: nodePackages$dev
            }
        },
        install: prototypeTasks.install.concat([
            'testData'
        ]),
        generateDefineModelScaffold: h.generateDefineModelScaffoldTask({
            settingFile: h.scaffoldSettingFilePath,
            destDir: 'serverside/model'
        }),
        generateDataSeedScaffold: h.generateDataSeedScaffoldTask({
            settingFile: h.scaffoldSettingFilePath,
            destDir: 'test/data/seeds'
        }),
        scaffold: [
            'generateDefineModelScaffold',
            'generateDataSeedScaffold'
        ],
        test: prototypeTasks.test.concat([

        ]),
        generateServersideUnitTestFiles: {
            config: {
                pattern: '+(batch|context|database|logger|middleware|model|request|response|server)/*.js'
            }
        },
        generateApiguide: {
            config: {
                src: prototypeTasks.generateApiguide.config.src
                    .map(function (filename) {
                        return path.resolve(path.dirname(prototypePath), filename)
                    })
                    .concat([
                        path.resolve('lib/**/*.js'),
                        path.resolve('task/**/*.js'),
                        path.resolve('README.md'),
                        path.resolve('Apemanfile.js'),
                        path.resolve('_apemanfile_helper.js')
                    ]),
                // Available themes:
                // [ "amelia","cerulean","cosmo","cyborg","flatly","journal","readable",
                //   "simplex","slate","spacelab","spruce","superhero","united"]
                theme: 'cyborg'
            }
        },
        generateCIConstantsJson: {
            config: {
                data: ciConstants
            }
        },
        generateDevConstantsJson: {
            config: {
                data: devConstants
            }
        },
        generateDocConstantsJson: {
            config: {
                data: docConstants
            }
        },
        generateScenarioTestConstantsJson: {
            config: {
                data: scenarioTestConstants
            }
        },
        generateBrowserScenarioTestConstantsJson: {
            config: {
                data: browserScenarioTestConstants
            }
        },
        generateProductionConstantsJson: {
            config: {
                data: productionConstants
            }
        },
        generateOperationConstantsJson: {
            config: {
                data: operationConstants
            }
        },
        generateOperationDevConstantsJson: {
            config: {
                data: operationDevConstants
            }
        },
        doc: prototypeTasks.doc.concat([

        ])
    };

    var libIndexTasks = h.libIndexTasks(['date', 'db', 'random', 'expression']);
    Object.keys(libIndexTasks).forEach(function (taskName) {
        tasks[taskName] = libIndexTasks[taskName];
        tasks.index.push(taskName);
    });
    tasks.generateLibDateIndex.config.capitalize = ['*_date'];

    var serversideIndexTasks = h.serversideIndexTasks(['database', 'model']);
    Object.keys(serversideIndexTasks).forEach(function (taskName) {
        tasks[taskName] = serversideIndexTasks[taskName];
        tasks.index.push(taskName);
    });

    //Create a new apeman file object.
    var apemanfile = new Apemanfile(
        prototype
    ).set({
            basedir: basedir,
            prototypePath: prototypePath,
            meta: meta,
            tasks: tasks,
            helper: h
        });
    process.chdir(cwd);
    return  apemanfile;
});
