'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.checkUpdate = undefined;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _electron = require('electron');

var _semver = require('semver');

var _semver2 = _interopRequireDefault(_semver);

var _bluebird = require('bluebird');

var _bluebird2 = _interopRequireDefault(_bluebird);

var _reactRemarkable = require('react-remarkable');

var _reactRemarkable2 = _interopRequireDefault(_reactRemarkable);

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new _bluebird2.default(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return _bluebird2.default.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

const { POI_VERSION, i18n, toggleModal, config, language } = window;
const __ = i18n.others.__.bind(i18n.others);

const request = _bluebird2.default.promisifyAll(require('request'));
const requestAsync = _bluebird2.default.promisify(request, { multiArgs: true });
const { updater } = process.platform !== 'linux' ? _electron.remote.require('./lib/updater') : {};

const { error } = require('../../lib/utils');

const LANG = ['zh-CN', 'zh-TW', 'en-US'];

const openHomePage = () => _electron.shell.openExternal('https://poi.io');

const doUpdate = (() => {
  var _ref = _asyncToGenerator(function* () {
    if (process.platform == 'win32') {
      try {
        yield updater.checkForUpdates();
        yield updater.downloadUpdate();
      } catch (e) {
        window.toast(__('Please try again or download manually.'), {
          type: 'danger',
          title: __('Update failed')
        });
      }
    }
  });

  return function doUpdate() {
    return _ref.apply(this, arguments);
  };
})();

if (process.platform === 'win32') {
  updater.on('update-available', () => {
    console.log('Update from poi.io available');
  });

  updater.on('update-downloaded', () => {
    window.toast(__('Quit app and install updates'), {
      type: 'success',
      title: __('Update successful')
    });
  });

  updater.on('update-not-available', () => {
    console.warn('Update from poi.io not available');
  });

  updater.on('error', (event, error) => {
    window.toast(__('Please try again or download manually'), {
      type: 'danger',
      title: __('Update failed')
    });
  });
}

const checkUpdate = exports.checkUpdate = (() => {
  var _ref2 = _asyncToGenerator(function* () {
    let response;
    let body;
    const betaChannel = config.get('poi.betaChannel', false);
    try {
      [response, body] = yield requestAsync(`https://${global.SERVER_HOSTNAME}/update/latest.json`, {
        method: 'GET',
        json: true,
        headers: {
          'User-Agent': `poi v${POI_VERSION}`
        }
      });
    } catch (e) {
      error(e.stack);
      console.warn('Check update error.');
    }

    if ((response || {}).statusCode === 200) {
      const version = betaChannel && _semver2.default.gt(body.betaVersion, body.version) ? body.betaVersion || 'v0.0.0' : body.version;
      const channel = version.includes('beta') ? '-beta' : '';
      console.log(`Remote version: ${version}. Current version: ${POI_VERSION}`);
      const knownVersion = config.get('poi.update.knownVersion', POI_VERSION);

      if (_semver2.default.lt(POI_VERSION, version) && _semver2.default.lt(knownVersion, version)) {
        let resp;
        let log;
        try {
          const currentLang = LANG.includes(language) ? language : 'en-US';[resp, log] = yield requestAsync(`https://${global.SERVER_HOSTNAME}/update/${currentLang}${channel}.md`, {
            method: 'GET',
            headers: {
              'User-Agent': `poi v${POI_VERSION}`
            }
          });
          if ((resp || {}).statusCode != 200) {
            console.warn('fetch update log error');
            log = '';
          }
          toggleUpdate(version, log);
        } catch (e) {
          error(e.stack);
          console.warn('fetch update log error');
        }
      }
    }
  });

  return function checkUpdate() {
    return _ref2.apply(this, arguments);
  };
})();

const toggleUpdate = (version, log) => {
  const title = _react2.default.createElement(
    'span',
    null,
    __('Update'),
    ' poi-v',
    version
  );
  // react-remarkable uses remarkable as parser，
  // remarkable disables HTML by default，
  // react-remarkable's default option dose not enable HTML，
  // it could be considered safe
  const content = _react2.default.createElement(_reactRemarkable2.default, { source: log });
  const footer = [{
    name: __('I know'),
    func: () => config.set('poi.update.knownVersion', version),
    style: 'success'
  }, {
    name: `${__('Manually download')}`,
    func: openHomePage,
    style: 'primary'
  }];
  if (process.platform === 'win32') {
    footer.push({
      name: `${__('Auto update')}`,
      func: doUpdate,
      style: 'primary'
    });
  }
  toggleModal(title, content, footer);
};

if (config.get('poi.update.enable', true)) {
  setTimeout(checkUpdate, 5000);
}