"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _react() {
  const data = _interopRequireDefault(require("react"));

  _react = function _react() {
    return data;
  };

  return data;
}

function _events() {
  const data = require("events");

  _events = function _events() {
    return data;
  };

  return data;
}

var _enum = require("./enum");

var _Logger = _interopRequireDefault(require("./Logger"));

var _exec = _interopRequireDefault(require("../util/exec"));

var _tasks = require("./tasks");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _createForOfIteratorHelper(o) { if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (o = _unsupportedIterableToArray(o))) { var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var it, normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

class Flow extends _events().EventEmitter {
  // 用户取消
  constructor({
    api
  }) {
    super();
    this.api = void 0;
    this.ctx = void 0;
    this.tasks = [];
    this.isCancel = false;
    this.logger = void 0;
    this.proc = void 0;
    this.state = _enum.FlowState.INIT;
    this.api = api;
    this.logger = new _Logger.default();
    this.logger.on('log', data => {
      this.emit('log', data);
    });
    this.ctx = {
      execa: (0, _exec.default)(this.logger, this.setProcRef.bind(this)),
      api: this.api,
      logger: this.logger,
      stages: {},
      result: {}
    };
    this.registryTasks();
  }

  run(args) {
    var _this = this;

    return _asyncToGenerator(function* () {
      _this.state = _enum.FlowState.ING;
      let hasBreak = false;

      var _iterator = _createForOfIteratorHelper(_this.tasks),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          const _step$value = _step.value,
                name = _step$value.name,
                task = _step$value.task,
                state = _step$value.state;

          // 用户取消任务
          if (_this.isCancel) {
            hasBreak = true;

            _this.setStepState(name, _enum.StepState.CANCEL);

            break;
          }

          if (state === _enum.StepState.SUCCESS) {
            continue;
          }

          try {
            yield task(_this.ctx, args);

            _this.setStepState(name, _enum.StepState.SUCCESS);
          } catch (e) {
            console.error('Execute task error', e);
            hasBreak = true;
            /**
             * 抛错有两种情况
             *  1. 任务执行出错
             *  2. 用户取消后，会杀死子进程，子进程可能 edit(1)
             */

            if (!_this.isCancel) {
              _this.state = _enum.FlowState.FAIL;

              _this.setStepState(name, _enum.StepState.FAIL);

              _this.emit('state', _objectSpread({}, args, {
                state: _enum.FlowState.FAIL
              }));

              _this.emit('log', {
                data: `\n🚧  Execute task error: ${e.message}\n`
              });
            }

            break;
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }

      if (hasBreak) {
        return _this.ctx.result;
      } // 完成之后触发一下完成事件，前端更新一下按钮状态


      _this.state = _enum.FlowState.SUCCESS;
      const generator = _this.ctx.stages.generator;

      _this.emit('state', {
        data: _objectSpread({}, args, {
          previewUrl: `http://localhost:${process.env.PORT || '8000'}${generator.path.toLowerCase()}`
        }),
        state: _enum.FlowState.SUCCESS
      }); // 清空日志


      _this.logger.clear();

      return _this.ctx.result;
    })();
  }

  cancel() {
    if (this.state !== _enum.FlowState.ING) {
      const err = new Error(`Error state(${this.state}) to terminated`);
      err.name = 'FlowError';
      throw err;
    }

    this.isCancel = true;
    this.state = _enum.FlowState.CANCEL;

    if (this.proc) {
      this.proc.kill('SIGTERM');
    }

    setTimeout(() => {
      this.emit('log', {
        data: '\n🛑  Stopped task success!\n'
      });
    }, 2000);
  }
  /**
   * 重试
   */


  retry(args) {
    var _this2 = this;

    return _asyncToGenerator(function* () {
      if (_this2.state !== _enum.FlowState.FAIL) {
        const err = new Error(`Error state(${_this2.state}) to retry`);
        err.name = 'FlowError';
        throw err;
      }

      return _this2.run(args);
    })();
  }

  getLog() {
    return this.logger.getLog();
  }

  getBlockUrl() {
    if (this.state !== _enum.FlowState.ING) {
      return '';
    }

    return this.ctx.result.blockUrl;
  }

  setStepState(taskName, state) {
    const curTask = this.tasks.find(({
      name
    }) => name === taskName);

    if (!curTask) {
      return;
    }

    curTask.state = state;
  }

  registryTasks() {
    [{
      name: 'parseUrl',
      task: _tasks.parseUrl
    }, {
      name: 'gitClone',
      task: _tasks.gitClone
    }, {
      name: 'gitUpdate',
      task: _tasks.gitUpdate
    }, {
      name: 'install',
      task: _tasks.install
    }, {
      name: 'runGenerator',
      task: _tasks.runGenerator
    }, {
      name: 'writeRoutes',
      task: _tasks.writeRoutes
    }].forEach(({
      name,
      task
    }) => {
      this.tasks.push({
        name,
        task,
        state: _enum.StepState.INIT
      });
    });
  }

  setProcRef(proc) {
    this.proc = proc;
  }

}

var _default = Flow;
exports.default = _default;