check = require("validator").check
HAPINode = require("hapilib").HAPINode

class CodeExchanger

    constructor: ->
        @client = new HAPINode
        @routes =
            "/exchangeCode": (req, res) => @exchangeCodeForToken(req, res)

    init: (@hapiEndPoint, @clientId, @secret, @instanceId) ->
        check(@hapiEndPoint).isUrl()
        @client.setBaseUrl @hapiEndPoint
        
    requestsHandler: ->
        return (req, res, next) =>
            handler = @routes[req.url]
            return next() unless handler
            handler(req, res)

    exchangeCodeForToken: (req, res) ->
        return res.send 400, "Bad Request" unless req.body?.code?
        code = req.body.code
        @client.post "/auth/code/exchange?authCode=#{code}&instanceId=#{@instanceId}", clientSecret: @secret, (err, tokenData) ->
            if err?
                return res.send err.statusCode, err.message
            res.send 200, tokenData

module?.exports = CodeExchanger
