'use strict'

/**
 * proxy api http request to rongxin.gov.rgvn.api service
 */

const proxy = require('http-proxy-middleware')
const config = require('config')
const logFactory = require('../utils/logFactory')
const logUtil = require('../utils/logUtil')
const debug = logFactory(logUtil())('rongxin.gov.rgvn.dashboard.tiandeng:routes:apiProxy')

class ApiProxy {

	constructor(policyRouter) {
		this._policyRouter = policyRouter
	}

	onProxyReq (proxyReq, req, res, options) {
		const method = 'proxyReq'
		debug(method, '[Proxy-Enter]', req.path)
    if (req.path.startsWith('/api')) {
			proxyReq.path = proxyReq.path.substring(4)
			debug(method, 'proxyReq.path: ', proxyReq.path, req.path)
		}
	}

	onProxyRes (proxyRes, req, res) {
		let method = "onProxyRes"
		debug('[Proxy-Exit]', req.path)
		debug('[onProxyRes] ', 'req.path = ', req.path, 'req.method = ', req.method)
	}

	onError (err, req, res) {
		let method = 'onError'
		debug.error(method, err)
	}

	init () {
		const self = this
		const govRgvnApiServiceUrl = `${config.get('rongxin_gov_rgvn_api_service').host}:${config.get('rongxin_gov_rgvn_api_service').port}`;

		const proxyInst = proxy({
			target: govRgvnApiServiceUrl,
			router: {
			},
			changeOrigin: true,
			logLevel: 'debug',
			logProvider: () => debug,
			onProxyRes: self.onProxyRes.bind(self),
			onProxyReq: self.onProxyReq.bind(self),
			onError: self.onError.bind(self)
		})

		self._policyRouter.use('/api', proxyInst, {
			name: 'apiProxy.proxyInst'
		});

		debug.info(`api proxy, api service uri: ${govRgvnApiServiceUrl}`)

		return self
	}
}

module.exports = ApiProxy
