'use strict';

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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _electron = require('electron');

var _divider = require('../components/divider');

var _divider2 = _interopRequireDefault(_divider);

var _reactBootstrap = require('react-bootstrap');

var _reactRedux = require('react-redux');

var _lodash = require('lodash');

var _glob = require('glob');

var _checkbox = require('../components/checkbox');

var _checkbox2 = _interopRequireDefault(_checkbox);

var _update = require('views/services/update');

var _contributors = require('poi-asset-contributor-data/dist/contributors.json');

var _contributors2 = _interopRequireDefault(_contributors);

var _reactFontawesome = require('react-fontawesome');

var _reactFontawesome2 = _interopRequireDefault(_reactFontawesome);

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

var _nodeFetch2 = _interopRequireDefault(_nodeFetch);

var _downloadProgress = require('./download-progress');

var _downloadProgress2 = _interopRequireDefault(_downloadProgress);

var _appMetrics = require('./app-metrics');

var _appMetrics2 = _interopRequireDefault(_appMetrics);

require('../assets/misc.css');

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 { ROOT, POI_VERSION, CONST, i18n, config } = window;
const __ = i18n.setting.__.bind(i18n.setting);
const { changeChannel } = process.platform !== 'linux' ? _electron.remote.require('./lib/updater') : {};

config.on('config.set', (path, value) => {
  if (path === 'poi.betaChannel' && process.platform !== 'linux') {
    changeChannel(value ? "beta" : "latest");
  }
});

const serverList = ["https://poi.io/fcd/", "https://raw.githubusercontent.com/poooi/poi/master/assets/data/fcd/", "http://7xj6zx.com1.z0.glb.clouddn.com/"];

const fetchHeader = new Headers();
fetchHeader.set("Cache-Control", "max-age=0");
const defaultFetchOption = {
  method: "GET",
  cache: "default",
  headers: fetchHeader
};

const getAvatarUrl = url => /.*githubusercontent.com\/u\/.*/.test(url) ? `${url}&s=160` : url;

const initState = {};

function _ref(res) {
  return res.ok ? res.json() : undefined;
}

function _ref2(e) {
  return undefined;
}

function _ref3(res) {
  return res.ok ? res.json() : undefined;
}

function _ref4(e) {
  return undefined;
}

function _ref5(fcd) {
  return fcd ? _react2.default.createElement(
    'span',
    { key: fcd[0] },
    fcd[0],
    ': ',
    _react2.default.createElement(
      _reactBootstrap.Label,
      { bsStyle: 'primary' },
      fcd[1]
    )
  ) : null;
}

const Misc = (0, _reactRedux.connect)(state => ({
  version: state.fcd.version || initState,
  layout: (0, _lodash.get)(state, 'config.poi.layout', 'horizontal')
}))(class Misc extends _react.Component {
  constructor(...args) {
    var _temp, _this;

    return _temp = _this = super(...args), this.updateData = (cacheMode = 'default') => _asyncToGenerator(function* () {
      // Update from local
      const localFileList = (0, _glob.sync)(`${ROOT}/assets/data/fcd/*`);
      for (const file of localFileList) {
        if (!file.includes('meta.json')) {
          const data = require(file);
          const version = (0, _lodash.get)(data, 'meta.version');
          const name = (0, _lodash.get)(data, 'meta.name');
          if (name && version) {
            const localVersion = (0, _lodash.get)(_this.props.version, name, '1970/01/01/01');
            if (version > localVersion) {
              _this.props.dispatch({
                type: '@@updateFCD',
                value: data
              });
            }
          }
        }
      }
      // Update from server
      let flag;
      for (const server of serverList) {
        flag = true;

        const fileList = yield yield (0, _nodeFetch2.default)(`${server}meta.json`, defaultFetchOption).then(_ref).catch(_ref2);
        if (fileList) {
          for (const file of fileList) {
            const localVersion = (0, _lodash.get)(_this.props.version, file.name, '1970/01/01/01');
            if (file.version > localVersion) {
              // eslint-disable-next-line no-console
              console.log(`Updating ${file.name}: current ${localVersion}, remote ${file.version}, mode ${cacheMode}`);

              const data = yield (0, _nodeFetch2.default)(`${server}${file.name}.json`, defaultFetchOption).then(_ref3).catch(_ref4);
              if (data) {
                _this.props.dispatch({
                  type: '@@updateFCD',
                  value: data
                });
              } else {
                flag = false;
              }
            } else {
              // eslint-disable-next-line no-console
              console.log(`No newer version of ${file.name}: current ${localVersion}, remote ${file.version}, mode ${cacheMode}`);
            }
          }
        } else {
          flag = false;
        }
        if (flag) {
          // eslint-disable-next-line no-console
          console.log(`Update fcd from ${server} successfully in mode ${cacheMode}.`);
          break;
        } else {
          console.warn(`Update fcd from ${server} failed in mode ${cacheMode}.`);
        }
      }
    }), _temp;
  }

  componentDidMount() {
    this.updateData()();
  }
  render() {
    const fcds = Object.keys(this.props.version || {}).map(key => [key, this.props.version[key]]);
    return _react2.default.createElement(
      'div',
      { id: 'poi-others', className: 'poi-others' },
      _react2.default.createElement(
        _reactBootstrap.Grid,
        null,
        _react2.default.createElement(
          _reactBootstrap.Col,
          { xs: 12 },
          _react2.default.createElement('img', { src: `file://${ROOT}/assets/img/logo.png`, style: { width: '100%' } })
        )
      ),
      _react2.default.createElement(
        _reactBootstrap.Grid,
        null,
        _react2.default.createElement(
          _reactBootstrap.Row,
          null,
          _react2.default.createElement(
            _reactBootstrap.Col,
            { xs: 6 },
            _react2.default.createElement(_divider2.default, { text: `${__("Current version")}: ${POI_VERSION}` })
          ),
          _react2.default.createElement(
            _reactBootstrap.Col,
            { xs: 6 },
            _react2.default.createElement(_downloadProgress2.default, null)
          )
        )
      ),
      _react2.default.createElement(
        _reactBootstrap.Grid,
        null,
        _react2.default.createElement(
          _reactBootstrap.Col,
          { xs: 6 },
          _react2.default.createElement(
            _reactBootstrap.Button,
            { onClick: _update.checkUpdate },
            __("Check Update")
          )
        ),
        _react2.default.createElement(
          _reactBootstrap.Col,
          { xs: 6 },
          _react2.default.createElement(_checkbox2.default, {
            label: __('Check update of beta version'),
            configName: 'poi.betaChannel',
            defaultVal: false })
        ),
        _react2.default.createElement(
          _reactBootstrap.Col,
          { xs: 12 },
          _react2.default.createElement(
            'p',
            null,
            __("poi-description %s", process.versions.electron)
          ),
          _react2.default.createElement(
            'div',
            { className: 'desc-buttons' },
            ['zh-CN', 'zh-TW'].includes(window.language) && _react2.default.createElement(
              _reactBootstrap.Button,
              { onClick: _electron.shell.openExternal.bind(this, 'http://weibo.com/letspoi') },
              _react2.default.createElement(_reactFontawesome2.default, { name: 'weibo' }),
              ' @\u4ECA\u5929poi\u51FA\u65B0\u7248\u672C\u4E86\u5417'
            ),
            ['zh-CN', 'zh-TW'].includes(window.language) ? _react2.default.createElement(
              _reactBootstrap.Button,
              null,
              _react2.default.createElement(_reactFontawesome2.default, { name: 'qq' }),
              ' \u7528\u6237\u4EA4\u6D41\u7FA4\uFF1A 378320628 '
            ) : _react2.default.createElement(
              _reactBootstrap.Button,
              { onClick: _electron.shell.openExternal.bind(this, 'https://discordapp.com/channels/118339803660943369/367575898313981952') },
              'Discord channel'
            ),
            _react2.default.createElement(
              _reactBootstrap.Button,
              { onClick: _electron.shell.openExternal.bind(this, 'http://db.kcwiki.moe') },
              _react2.default.createElement(_reactFontawesome2.default, { name: 'database' }),
              ' ',
              __("Database")
            ),
            _react2.default.createElement(
              _reactBootstrap.Button,
              { onClick: _electron.shell.openExternal.bind(this, 'https://github.com/poooi/poi/wiki') },
              _react2.default.createElement(_reactFontawesome2.default, { name: 'question' }),
              ' ',
              __("Wiki")
            ),
            _react2.default.createElement(
              _reactBootstrap.Button,
              { onClick: _electron.shell.openExternal.bind(this, 'https://github.com/poooi/poi') },
              _react2.default.createElement(_reactFontawesome2.default, { name: 'github' }),
              ' GitHub'
            ),
            _react2.default.createElement(
              _reactBootstrap.Button,
              { onClick: _electron.shell.openExternal.bind(this, 'https://opencollective.com/poi') },
              'OpenCollective'
            )
          )
        )
      ),
      _react2.default.createElement(_divider2.default, { text: __("Data version") }),
      _react2.default.createElement(
        _reactBootstrap.Grid,
        null,
        _react2.default.createElement(
          _reactBootstrap.Col,
          { xs: 12 },
          fcds.map(_ref5)
        ),
        _react2.default.createElement(
          _reactBootstrap.Col,
          { xs: 12 },
          _react2.default.createElement(
            _reactBootstrap.Button,
            { onClick: this.updateData('reload') },
            __("Update data")
          )
        )
      ),
      _react2.default.createElement(_divider2.default, { text: __('Performance Monitor') }),
      _react2.default.createElement(
        _reactBootstrap.Col,
        { xs: 12 },
        _react2.default.createElement(_appMetrics2.default, null)
      ),
      _react2.default.createElement(_divider2.default, { text: 'Contributors' }),
      _react2.default.createElement(
        _reactBootstrap.Grid,
        null,
        _react2.default.createElement(
          _reactBootstrap.Col,
          { xs: 12, className: 'contributors' },
          _contributors2.default.map((e, i) => _react2.default.createElement(
            'div',
            { key: i, className: 'contributor-item' },
            _react2.default.createElement('img', {
              className: 'avatar-img',
              src: getAvatarUrl(e.avatar_url),
              onClick: _electron.shell.openExternal.bind(this, e.html_url),
              title: e.name || e.login
            })
          ))
        )
      ),
      _react2.default.createElement(_divider2.default, { text: 'OpenCollective' }),
      _react2.default.createElement(
        _reactBootstrap.Grid,
        { className: 'opencollective container' },
        _react2.default.createElement(
          _reactBootstrap.Col,
          { xs: 12 },
          _react2.default.createElement(
            'div',
            null,
            _react2.default.createElement(
              'a',
              { href: 'https://opencollective.com/poi/sponsor/0/website' },
              _react2.default.createElement('img', { src: 'https://opencollective.com/poi/sponsor/0/avatar.svg' })
            ),
            _react2.default.createElement(
              'a',
              { href: 'https://opencollective.com/poi/sponsor/1/website' },
              _react2.default.createElement('img', { src: 'https://opencollective.com/poi/sponsor/1/avatar.svg' })
            ),
            _react2.default.createElement(
              'a',
              { href: 'https://opencollective.com/poi/sponsor/2/website' },
              _react2.default.createElement('img', { src: 'https://opencollective.com/poi/sponsor/2/avatar.svg' })
            ),
            _react2.default.createElement(
              'a',
              { href: 'https://opencollective.com/poi/sponsor/3/website' },
              _react2.default.createElement('img', { src: 'https://opencollective.com/poi/sponsor/3/avatar.svg' })
            ),
            _react2.default.createElement(
              'a',
              { href: 'https://opencollective.com/poi/sponsor/4/website' },
              _react2.default.createElement('img', { src: 'https://opencollective.com/poi/sponsor/4/avatar.svg' })
            ),
            _react2.default.createElement(
              'a',
              { href: 'https://opencollective.com/poi/sponsor/5/website' },
              _react2.default.createElement('img', { src: 'https://opencollective.com/poi/sponsor/5/avatar.svg' })
            ),
            _react2.default.createElement(
              'a',
              { href: 'https://opencollective.com/poi/sponsor/6/website' },
              _react2.default.createElement('img', { src: 'https://opencollective.com/poi/sponsor/6/avatar.svg' })
            ),
            _react2.default.createElement(
              'a',
              { href: 'https://opencollective.com/poi/sponsor/7/website' },
              _react2.default.createElement('img', { src: 'https://opencollective.com/poi/sponsor/7/avatar.svg' })
            ),
            _react2.default.createElement(
              'a',
              { href: 'https://opencollective.com/poi/sponsor/8/website' },
              _react2.default.createElement('img', { src: 'https://opencollective.com/poi/sponsor/8/avatar.svg' })
            ),
            _react2.default.createElement(
              'a',
              { href: 'https://opencollective.com/poi/sponsor/9/website' },
              _react2.default.createElement('img', { src: 'https://opencollective.com/poi/sponsor/9/avatar.svg' })
            )
          ),
          _react2.default.createElement(
            'div',
            null,
            _react2.default.createElement(
              'a',
              { href: 'https://opencollective.com/poi#backers' },
              _react2.default.createElement('img', { src: `https://opencollective.com/poi/backers.svg?width=${this.props.layout === 'horizontal' ? 450 : 900}` })
            )
          )
        )
      ),
      _react2.default.createElement(_divider2.default, { text: 'Special Thanks To' }),
      _react2.default.createElement(
        _reactBootstrap.Grid,
        { className: 'thanks-to sp-thanks-to' },
        _react2.default.createElement(
          'div',
          { className: 'div-row thanks-to-item' },
          _react2.default.createElement(
            'div',
            { className: 'thanks-to-img-container' },
            _react2.default.createElement('img', { className: 'thanks-to-img',
              src: 'https://upload.kcwiki.moe/commons/thumb/d/d1/Kcwiki-banner.png/600px-Kcwiki-banner.png',
              style: {
                WebkitClipPath: 'inset(0px 78% 0px 0px)',
                maxHeight: '100%',
                marginLeft: '5%'
              },
              onClick: _electron.shell.openExternal.bind(this, 'https://zh.kcwiki.moe/wiki/%E8%88%B0%E5%A8%98%E7%99%BE%E7%A7%91'),
              title: 'KCWiki'
            })
          ),
          _react2.default.createElement(
            'div',
            { className: 'thanks-to-container' },
            _react2.default.createElement(
              'b',
              null,
              'KCWiki'
            ),
            _react2.default.createElement(
              'p',
              null,
              'For sponsing poi data server, providing data of item imporvment, task info, shipgirl qoutes, etc.'
            )
          )
        )
      ),
      _react2.default.createElement(_divider2.default, { text: 'Thanks To' }),
      _react2.default.createElement(
        _reactBootstrap.Grid,
        { className: 'thanks-to' },
        CONST.thanksTo.map((e, i) => _react2.default.createElement(
          'div',
          { className: 'div-row thanks-to-item', key: i },
          _react2.default.createElement(
            'div',
            { className: 'thanks-to-img-container' },
            _react2.default.createElement('img', { className: 'thanks-to-img', src: e.avatar, style: e.extraCSS, onClick: _electron.shell.openExternal.bind(this, e.link), title: e.name })
          ),
          _react2.default.createElement(
            'div',
            { className: 'thanks-to-container' },
            _react2.default.createElement(
              'b',
              null,
              e.name
            ),
            _react2.default.createElement(
              'p',
              null,
              e.description
            )
          )
        ))
      )
    );
  }
});

exports.default = Misc;
module.exports = exports['default'];