'use strict';
const Controller = require('egg').Controller;

class ProxyController extends Controller {
  async info() {
    const { ctx } = this;
    ctx.body = {
      name: `hello ${ctx.params.id}`,
    };
  }


  getOptions() {
    const { ctx, config } = this;
    const { url, type } = ctx;

    let catalog = url.substring(1, url.indexOf('/', 1));
    let pathUrl = url.substring(url.indexOf('/', 1));
    let fullPath = '/' + catalog + config.restful.version + pathUrl;

    return {
      'host': config.restful.host, //后台请求地址
      'port': config.restful.port,
      'path': fullPath,
      'method': type,
      'agent': false,
      'headers': {
        "Accept": "application/json",
        "Content-Type": "application/json",
        'User-Agent': 'Request for Express'
      }
    };
  }

  addToken(options) {
    const { ctx } = this;

    if (ctx.session.passport && ctx.session.passport.user && ctx.session.passport.user && ctx.session.passport.user.token) {
      options.headers['Authorization'] = "Bearer " + ctx.session.passport.user.token;
    }

    if (ctx.headers['device-id']) {
      options.headers['Device-Id'] = ctx.headers['device-id'];
    }

    if (ctx.ip) {
      options.headers['Client-Ip'] = ctx.ip;
    }

    return options;
  }


  splitUrl(fullUrl) {
    const { config } = this;

    if (config.prefix && config.prefix.length > 1) {
      fullUrl = fullUrl.substring(config.prefix.length - 1);
    }

    return fullUrl.substring(4);
  }


  async get() {
    const { ctx, config, logger } = this;
    const { originalUrl } = ctx;
    const { restful = {} } = config;
    const { host } = restful;
    const { access_token } = ctx.session.user_info;
    const url = originalUrl.substring(4); 

    const result = await ctx.curl(`${host}${url}`, {
      method: 'GET',
      dataType: 'json',
      headers: {
        'authorization': `Bearer ${access_token}`,
        'accept': 'application/json',
        'content-type': 'application/json'
      },
      timeout: [5000, 60000]
    });

    logger.info(
      "proxy url:",
      `${host}${url}`,
      'headers:',
      {
        'authorization': `Bearer ${access_token}`,
        'accept': 'application/json',
        'content-type': 'application/json'
      },
      "result:",
      result
    );

    ctx.body = result.data;

    return ctx.body;
  }
}

module.exports = ProxyController;