"use strict";

var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
_Object$defineProperty(exports, "__esModule", {
  value: true
});
exports.bundleRouter = bundleRouter;
exports.debugRouter = debugRouter;
exports.indexRouter = indexRouter;
exports.poststdbgRouter = poststdbgRouter;
exports.startDebug = startDebug;
var _stringify = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/json/stringify"));
var _path = _interopRequireDefault(require("path"));
var _child_process = require("child_process");
var _qrImage = _interopRequireDefault(require("qr-image"));
var _openBrowser = require("./openBrowser.js");
var _index = require("../cli-shared-utils/index.js");
var _recordClient = require("./record-client.js");
var _requestIde = require("../utils/requestIde.js");
function indexRouter(context) {
  // 默认展示二维码
  const image = _qrImage.default.image(`http://${context.host}`, {
    size: 9,
    type: 'png',
    ec_level: 'H'
  });
  context.type = 'image/png';
  context.body = image;
}
function debugRouter(context) {
  const str = context.request.querystring;
  const ip = str.replace('ip=', '');
  const url = `chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=${ip}:5086/00010002-0003-4004-8005-000600070008`;
  context.response.type = 'html';
  context.response.body = `<p>请复制以下地址到地址栏里面访问（某些高版本chorme可能会导致地址访问不了，去掉“chorme-”尝试下）</p><p>${url}</p>`;
}
function poststdbgRouter(context, args) {
  const params = (0, _recordClient.getDebugInfoFromRequest)(context.request);
  const {
    ip,
    supportNewDev = false
  } = context.request.body;
  let host = context.request.host;
  const portRegex = /:(\d+)/;
  const match = host.match(portRegex);
  const port = match ? match[1] : '';
  if (port) {
    host = '127.0.0.1:' + port;
  }

  // ADB调试模式
  if (params.linkMode === _recordClient.LINK_MODE.ADB) {
    startDebug(context, params, supportNewDev, args);
    return;
  }
  (0, _index.info)((0, _stringify.default)(params));

  // 处理chrome调试自动打开逻辑
  let url = '';
  if (params.application && params.application.includes('vivo')) {
    url = `http://${host}/front_end/inspector.html?ws=${ip}:${params.devicePort}/inspector&remoteFrontend=true&dockSide=undocked&panel=console`;
  } else if (params.application && params.application.includes('honor')) {
    url = `http://${host}/front_end/inspector.html?ws=${params.ws}&remoteFrontend=true&dockSide=undocked&panel=console`;
  } else if (params.application && params.application.includes('mi')) {
    url = `http://${host}/front_end/inspector.html?ws=${params.ws}&remoteFrontend=true&dockSide=undocked&panel=console`;
  } else if (params.application && params.application.includes('OPPO')) {
    url = `http://${host}/front_end/inspector.html?ws=${params.ws}&remoteFrontend=true&dockSide=undocked&panel=console`;
  }
  if (args.ide) {
    (0, _requestIde.fetchInfo)({
      devicePort: params.devicePort,
      deviceIp: ip || params.ws.split(':')[0],
      isAdbDebug: false,
      ws: params.ws || '',
      application: params.application || ''
    }, 'postDebug');
    // ide环境不打开浏览器
    return;
  }

  // 使用本地的devtool来打开调试页面
  (0, _openBrowser.openBrowser)(url);
}

/**
 * 适配支持调试器的开始调试请求， 自动打开chrome进程
 */
async function startDebug(context, params, supportNewDev, args) {
  context.status = 200;
  const {
    sn,
    linkMode,
    devicePort
  } = params;
  let serverPort = devicePort;

  // ADB调试模式
  if (linkMode === _recordClient.LINK_MODE.ADB) {
    const {
      localReversePort,
      err
    } = await context.adbDebugger.forwardForWsChannel(sn, devicePort);
    if (err) {
      console.error(`startDebug(): adb forward 端口映射失败: ${err.message}`);
      return;
    }
    serverPort = localReversePort;
  }

  // 生成调试url，并且向页面输出调试APP信息
  let newDevUrl = '';
  if (params.application && params.application.includes('vivo')) {
    newDevUrl = `http://127.0.0.1:${serverPort}/front_end/inspector.html?ws=127.0.0.1:${devicePort}/inspector&remoteFrontend=true&dockSide=undocked&panel=console`;
  } else if (params.application && params.application.includes('honor')) {
    newDevUrl = `http://127.0.0.1:${serverPort}/front_end/inspector.html?ws=${params.ws}&remoteFrontend=true&dockSide=undocked&panel=console`;
  } else if (params.application && params.application.includes('mi')) {
    newDevUrl = `http://127.0.0.1:${serverPort}/front_end/inspector.html?ws=${params.ws}&remoteFrontend=true&dockSide=undocked&panel=console`;
  } else if (params.application && params.application.includes('OPPO')) {
    newDevUrl = `http://127.0.0.1:${serverPort}/front_end/inspector.html?ws=${params.ws}&remoteFrontend=true&dockSide=undocked&panel=console`;
  }
  if (args.ide) {
    (0, _requestIde.fetchInfo)({
      devicePort,
      deviceIp: '127.0.0.1',
      isAdbDebug: true,
      ws: params.ws || '',
      application: params.application || ''
    }, 'postDebug');
    // ide环境不打开浏览器
    return;
  }
  (0, _openBrowser.openBrowser)(newDevUrl);
}
function getProjectName() {
  const str = _index.fs.readFileSync(_path.default.resolve(_index.projectPath, './src/manifest.json'), 'utf8');
  return JSON.parse(str).package;
}
function bundleRouter(context) {
  const projectName = getProjectName();
  const projectDist = _path.default.join(_index.projectPath, `dist`);
  const files = _index.fs.readdirSync(projectDist);
  const rpkFiles = files.map(file => {
    if (file.endsWith('.rpk')) {
      const fileName = file.split('.rpk')[0];
      if (fileName.includes(projectName)) {
        return file;
      }
    }
  });
  let projectRpk = _path.default.join(projectDist, `${projectName}.rpk`);
  if (rpkFiles && rpkFiles.length > 0) {
    projectRpk = _path.default.resolve(projectDist, rpkFiles[0]);
  }
  if (_index.fs.existsSync(projectRpk)) {
    context.body = _index.fs.createReadStream(projectRpk);
    context.set('Content-Type', 'text/plain');
  } else {
    (0, _index.info)(`${projectDist}目录下没有rpk文件，现在运行npm run build命令进行打包`);
    (0, _child_process.execSync)('qg build', {
      cwd: _index.projectPath,
      stdio: 'inherit'
    });
  }
}