httpProxy = require "http-proxy"
url = require "url"

class HapiProxyMW

    forwardRegExp: RegExp "
\/assets.*
|\/categories.*
|\/representations.*
|\/layers.*
|\/games.*
|\/clients.*
|\/settings.*
|\/goods.*
|\/purchase.*
|\/users.*
|\/avatars.*
|\/auth.*
|\/me
|\/tokens.*
|\/forms*"

    proxyApiCalls: (pattern) ->
        (req, res, next) =>
            if req.url.match(pattern)
                @proxy.proxyRequest req, res
            else next()

    configure: ({app: app, callback: callback}) ->

        # loading and reading configuration variables
        Config = require "#{__dirname}/../config"
        Config.load()
        endPoint = Config.get "endPoint"
        host = url.parse(endPoint).host
        @proxy = new httpProxy.HttpProxy
            target:
                host: host
                port: 443
                https: true
        # proxying all HAPI calls
        # this needs to happen before the bodyParser
        # as it changes the req and res objects
        # breaking the http-proxy
        app.use(@proxyApiCalls(@forwardRegExp))

        callback()

module.exports = HapiProxyMW
