async = require "async"
path = require "path"
fs = require "fs"

class AppServerConfiguration

    @configFileName: "app.server.config.json"
    @defaultConfigFilePath: path.resolve(__dirname, "../default.#{@configFileName}")

    init: (@app) ->

    configure: (callback) ->
        configData = @loadConfiguration()

        configureFunctions = []
        for mod in configData
            f = do(mod) =>
                (callback) =>
                    error = null
                    try
                        # check if we are referencing a default module,
                        # by looking for it in the modules folder
                        realPath = path.join(__dirname, "modules", mod)
                        unless fs.existsSync "#{realPath}.coffee"
                            # otherwise we load the file specified
                            # based on the folder from where the
                            # process has been started
                            realPath = path.join(process.cwd(), mod)
                        c = require realPath
                        c = new c if typeof c is "function"
                    catch e
                        error = new Error("An error occured while loading App Server Module #{mod}")
                    return callback error, mod if error?
                    c.configure app: @app, callback: (err) ->
                        console.log "MiddleWare: #{mod} loaded"
                        callback(err, mod)
            configureFunctions.push f
        async.series configureFunctions, (err, results) ->
            callback?(err)

    loadConfiguration: ->
        configData = []
        try
            configData = require path.join(process.cwd(), @constructor.configFileName)
        catch e
            console.log "#{@constructor.configFileName} not found"
            configData = require @constructor.defaultConfigFilePath
        configData

module.exports = AppServerConfiguration
