utils = require 'utility'
rp = require 'request-promise'
BaseOauth = require './baseOauth'

class Oauth extends BaseOauth
  auth_url: (req) ->
    redirect_uri = "http://#{req.hostname}/oauth2/login?from=#{utils.base64encode req.query.redirect_uri}&appkey=#{req.query.appkey}"
    "#{@other_conf.login_url}?client_id=#{@other_conf.client_id}&redirect_uri=#{encodeURIComponent redirect_uri}&response_type=code"

  get_user_info: (req) ->
    redirect_uri = "http://#{req.hostname}#{req.originalUrl}"
    redirect_uri = redirect_uri.replace /&code=.*/, ''
    opts = {
      uri: @other_conf.api_url
      headers:
        'Authorization': utils.base64encode "#{@other_conf.client_id}:#{@other_conf.client_secret}"
      qs:
        grant_type: 'authorization_code'
        code: req.query.code
        redirect_uri: redirect_uri
        client_id: @other_conf.client_id
        client_secret: @other_conf.client_secret
      json: true
    }
    if @debug
      console.log opts
    rp opts

  get_openid: (data) ->
    data.uid

module.exports = Oauth