'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 _reactRemarkable = require('react-remarkable');

var _reactRemarkable2 = _interopRequireDefault(_reactRemarkable);

var _nodeFetch = require('node-fetch');

var _nodeFetch2 = _interopRequireDefault(_nodeFetch);

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(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 Promise.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 fetchHeader = new Headers();
fetchHeader.set("Cache-Control", "max-age=0");
fetchHeader.set('User-Agent', `poi v${POI_VERSION}`);
const defaultFetchOption = {
  method: "GET",
  cache: "default",
  headers: fetchHeader
};

const { updater } = process.platform !== 'linux' ? _electron.remote.require('./lib/updater') : {};
const LANG = ['zh-CN', 'zh-TW', 'en-US'];

function* _ref3() {
  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')
      });
    }
  }
}

const doUpdate = (() => {
  var _ref = _asyncToGenerator(_ref3);

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

function _ref4() {
  // eslint-disable-next-line no-console
  console.log('Update from poi.io available');
}

function _ref5() {
  window.toast(__('Quit app and install updates'), {
    type: 'success',
    title: __('Update successful')
  });
}

function _ref6() {
  console.warn('Update from poi.io not available');
}

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

if (process.platform === 'win32') {
  updater.on('update-available', _ref4);

  updater.on('update-downloaded', _ref5);

  updater.on('update-not-available', _ref6);

  updater.on('error', _ref7);
}

function _ref8(res) {
  return res.json();
}

function _ref9(e) {
  console.warn('Check update error.', e.stack);
  return {};
}

function _ref10(res) {
  return res.text();
}

function _ref11(res) {
  console.warn('fetch update log error');
  return "";
}

function* _ref12() {
  const betaChannel = config.get('poi.betaChannel', false);
  const versionInfo = yield (0, _nodeFetch2.default)(`https://${global.SERVER_HOSTNAME}/update/latest.json`, defaultFetchOption).then(_ref8).catch(_ref9);
  if (versionInfo.version) {
    const version = betaChannel && _semver2.default.gt(versionInfo.betaVersion, versionInfo.version) ? versionInfo.betaVersion || 'v0.0.0' : versionInfo.version;
    const channel = version.includes('beta') ? '-beta' : '';
    // eslint-disable-next-line no-console
    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)) {
      const currentLang = LANG.includes(language) ? language : 'en-US';
      const log = yield (0, _nodeFetch2.default)(`https://${global.SERVER_HOSTNAME}/update/${currentLang}${channel}.md`, defaultFetchOption).then(_ref10).catch(_ref11);
      toggleUpdate(version, log);
    }
  }
}

const checkUpdate = exports.checkUpdate = (() => {
  var _ref2 = _asyncToGenerator(_ref12);

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

function _ref13() {
  return _electron.shell.openExternal('https://poi.io');
}

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: _ref13,
    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);
}