'use strict';

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

var _class, _temp2;

var _pathExtra = require('path-extra');

var _pathExtra2 = _interopRequireDefault(_pathExtra);

var _electron = require('electron');

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

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

var _reactFontawesome2 = _interopRequireDefault(_reactFontawesome);

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

var _lodash = require('lodash');

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

var _reactFileDropzone = require('react-file-dropzone');

var _reactFileDropzone2 = _interopRequireDefault(_reactFileDropzone);

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

var _checkbox2 = _interopRequireDefault(_checkbox);

var _pluginManager = require('views/services/plugin-manager');

var _pluginManager2 = _interopRequireDefault(_pluginManager);

var _nameInput = require('./name-input');

var _nameInput2 = _interopRequireDefault(_nameInput);

var _installedPlugin = require('./installed-plugin');

var _installedPlugin2 = _interopRequireDefault(_installedPlugin);

var _uninstalledPlugin = require('./uninstalled-plugin');

var _uninstalledPlugin2 = _interopRequireDefault(_uninstalledPlugin);

require('../assets/plugins.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 __ = window.i18n.setting.__.bind(window.i18n.setting);

const { dialog } = _electron.remote.require('electron');
const { PLUGIN_PATH } = window;

function _ref4(state) {
  _pluginManager2.default.selectConfig(state, null, null);
}

function _ref15() {
  _electron.shell.openItem(_pathExtra2.default.join(PLUGIN_PATH, 'node_modules'));
}

function _ref16(e) {
  _electron.shell.openExternal("https://www.npmjs.com/search?q=poi-plugin");
  e.preventDefault();
}

const PluginConfig = (0, _reactRedux.connect)((state, props) => ({
  plugins: state.plugins,
  mirrorName: (0, _lodash.get)(state, 'config.packageManager.mirrorName', navigator.language === 'zh-CN' ? "taobao" : "npm"),
  proxy: (0, _lodash.get)(state, 'config.packageManager.proxy', false),
  betaCheck: (0, _lodash.get)(state, 'config.packageManager.enableBetaPluginCheck', false),
  autoUpdate: (0, _lodash.get)(state, 'config.packageManager.enableAutoUpdate', true)
}))((_temp2 = _class = class pluginConfig extends _react.Component {
  constructor(...args) {
    var _temp, _this;

    function* _ref7(index) {
      const plugin = _this.props.plugins[index];
      switch (_pluginManager2.default.getStatusOfPlugin(plugin)) {
        case _pluginManager2.default.DISABLED:
          yield _pluginManager2.default.enablePlugin(plugin);
          break;
        case _pluginManager2.default.VALID:
          yield _pluginManager2.default.disablePlugin(plugin);
          break;
      }
    }

    function* _ref8(name, e) {
      if ((0, _lodash.get)(e, 'target.disabled')) {
        return;
      }
      let installingPluginNames = _this.state.installingPluginNames.slice();
      installingPluginNames.push(name);
      _this.setState({
        installingPluginNames,
        npmWorking: true
      });
      try {
        yield _pluginManager2.default.installPlugin(name);
        installingPluginNames = _this.state.installingPluginNames.slice();
        const index = installingPluginNames.indexOf(name);
        if (index > -1) {
          installingPluginNames.splice(index, 1);
          _this.setState({
            installingPluginNames,
            npmWorking: false
          });
        }
      } catch (error) {
        _this.setState({ npmWorking: false });
        throw error;
      }
    }

    function* _ref11(index, e) {
      if ((0, _lodash.get)(e, 'target.disabled')) {
        return;
      }
      _this.setState({ npmWorking: true });
      const plugins = _pluginManager2.default.getInstalledPlugins();
      const plugin = plugins[index];
      if (plugin.linkedPlugin) {
        _this.setState({ npmWorking: false });
        return;
      }
      try {
        yield _pluginManager2.default.installPlugin(plugin.packageName, plugin.latestVersion);
      } catch (error) {
        throw error;
      } finally {
        _this.setState({ npmWorking: false });
      }
    }

    function* _ref12(e) {
      if ((0, _lodash.get)(e, 'target.disabled')) {
        return;
      }
      _this.setState({
        updatingAll: true,
        npmWorking: true
      });
      const plugins = _pluginManager2.default.getInstalledPlugins();
      for (const index in plugins) {
        if (plugins[index].isOutdated) {
          try {
            yield _this.handleUpdate(index);
          } catch (error) {
            throw error;
          }
        }
      }
      _this.setState({
        updatingAll: false,
        npmWorking: false
      });
    }

    function* _ref14(index, e) {
      if ((0, _lodash.get)(e, 'target.disabled')) {
        return;
      }
      _this.setState({ npmWorking: true });
      try {
        const plugins = _pluginManager2.default.getInstalledPlugins();
        const plugin = plugins[index];
        yield _pluginManager2.default.uninstallPlugin(plugin);
      } catch (error) {
        throw error;
      } finally {
        _this.setState({ npmWorking: false });
      }
    }

    function* _ref17() {
      const filenames = dialog.showOpenDialog({
        title: __('Select files'),
        defaultPath: _electron.remote.require('electron').app.getPath('downloads'),
        properties: ['openFile', 'multiSelections']
      });
      if (filenames) {
        for (const index in filenames) {
          const filename = filenames[index];
          _this.setState({ manuallyInstallStatus: 1 });
          try {
            yield _this.handleInstall(filename);
            _this.setState({ manuallyInstallStatus: 2 });
          } catch (error) {
            _this.setState({ manuallyInstallStatus: 3 });
          }
        }
      }
    }

    function* _ref18(droppedFiles) {
      const filenames = [];
      // droppedFiles is not an Array, but a FileList
      for (let i = 0; i < droppedFiles.length; i++) {
        filenames.push(droppedFiles[i].path);
      }
      if (filenames.length > 0) {
        for (const index in filenames) {
          const filename = filenames[index];
          _this.setState({ manuallyInstallStatus: 1 });
          try {
            yield _this.handleInstall(filename);
            _this.setState({ manuallyInstallStatus: 2 });
          } catch (error) {
            _this.setState({ manuallyInstallStatus: 3 });
          }
        }
      }
    }

    function* _ref19(name) {
      _this.setState({ manuallyInstallStatus: 1 });
      try {
        yield _this.handleInstall(name);
        _this.setState({ manuallyInstallStatus: 2 });
      } catch (error) {
        _this.setState({ manuallyInstallStatus: 3 });
      }
    }

    return _temp = _this = super(...args), this.state = {
      checkingUpdate: false,
      npmWorking: false,
      installingAll: false,
      installingPluginNames: [],
      updatingAll: false,
      reloading: false,
      advanced: false,
      manuallyInstallStatus: 0
    }, this.handleEnableBetaPluginCheck = () => {
      _pluginManager2.default.selectConfig(null, null, !this.props.betaCheck);
    }, this.handleEnableProxy = () => {
      _pluginManager2.default.selectConfig(null, !this.props.proxy, null);
    }, this.handleEnableAutoUpdate = () => {
      // unlike other options, autoUpdate will not write to npm conf
      window.config.set('packageManager.enableAutoUpdate', !this.props.autoUpdate);
    }, this.onSelectServer = _ref4, this.handleAdvancedShow = () => {
      this.setState({ advanced: !this.state.advanced });
    }, this.handleEnable = (() => {
      var _ref = _asyncToGenerator(_ref7);

      return function (_x) {
        return _ref.apply(this, arguments);
      };
    })(), this.handleInstall = (() => {
      var _ref2 = _asyncToGenerator(_ref8);

      return function (_x2, _x3) {
        return _ref2.apply(this, arguments);
      };
    })(), this.handleUpdate = (() => {
      var _ref3 = _asyncToGenerator(_ref11);

      return function (_x4, _x5) {
        return _ref3.apply(this, arguments);
      };
    })(), this.handleInstallAll = _asyncToGenerator(function* () {
      _this.setState({
        installingAll: true,
        npmWorking: true
      });
      const settings = _pluginManager2.default.getUninstalledPluginSettings();
      for (const name in settings) {
        try {
          yield _this.handleInstall(name);
        } catch (e) {
          console.error(e);
        }
      }
      _this.setState({
        installingAll: false,
        npmWorking: false
      });
    }), this.handleUpdateAll = (() => {
      var _ref5 = _asyncToGenerator(_ref12);

      return function (_x6) {
        return _ref5.apply(this, arguments);
      };
    })(), this.handleRemove = (() => {
      var _ref6 = _asyncToGenerator(_ref14);

      return function (_x7, _x8) {
        return _ref6.apply(this, arguments);
      };
    })(), this.checkUpdate = _asyncToGenerator(function* () {
      _this.setState({
        checkingUpdate: true,
        npmWorking: true
      });
      yield _pluginManager2.default.getOutdatedPlugins();
      _this.setState({
        checkingUpdate: false,
        npmWorking: false
      });
    }), this.onSelectOpenFolder = _ref15, this.onSelectOpenSite = _ref16, this.onSelectInstallFromFile = () => {
      this.synchronize(_asyncToGenerator(_ref17));
    }, this.onDropInstallFromFile = (() => {
      var _ref9 = _asyncToGenerator(_ref18);

      return function (_x9) {
        return _ref9.apply(this, arguments);
      };
    })(), this.handleManuallyInstall = (() => {
      var _ref10 = _asyncToGenerator(_ref19);

      return function (_x10) {
        return _ref10.apply(this, arguments);
      };
    })(), this.handleGracefulRepair = _asyncToGenerator(function* () {
      _this.setState({
        npmWorking: true
      });
      try {
        yield _pluginManager2.default.gracefulRepair();
      } catch (e) {
        console.error(e);
      } finally {
        _this.setState({
          npmWorking: false
        });
      }
    }), this.synchronize = callback => {
      if (this.lock) {
        return;
      }
      this.lock = true;
      callback();
      this.lock = false;
    }, this.componentDidUpdate = (prevProps, prevState) => {
      if (prevState.manuallyInstallStatus > 1 && prevState.manuallyInstallStatus === this.state.manuallyInstallStatus) {
        this.setState({ manuallyInstallStatus: 0 });
      }
    }, this.componentDidMount = _asyncToGenerator(function* () {
      _this.setState({
        checkingUpdate: true,
        npmWorking: true
      });
      const isNotif = window.config.get('config.packageManager.enablePluginCheck', true) && !_this.props.autoUpdate; // if we auto update plugins, don't toast notify

      function* _ref20() {
        yield _pluginManager2.default.getOutdatedPlugins(isNotif);
        if (_this.props.autoUpdate) {
          const plugins = _pluginManager2.default.getInstalledPlugins();
          for (const index in plugins) {
            if (plugins[index].isOutdated) {
              try {
                yield _this.handleUpdate(index);
              } catch (error) {
                throw error;
              }
            }
          }
        }
      }

      const handleAutoUpdate = (() => {
        var _ref13 = _asyncToGenerator(_ref20);

        return function handleAutoUpdate() {
          return _ref13.apply(this, arguments);
        };
      })();
      _pluginManager2.default.on('initialized', handleAutoUpdate);
      _this.setState({
        checkingUpdate: false,
        npmWorking: false
      });
    }), _temp;
  }

  render() {
    const uninstalledPluginSettings = _pluginManager2.default.getUninstalledPluginSettings();
    const mirrors = _pluginManager2.default.getMirrors();
    const updateStatusFAname = this.state.updatingAll ? 'spinner' : 'cloud-download';
    const installStatusFAname = this.state.installingAll ? 'spinner' : 'download';
    let installStatusbsStyle, installStatusText;
    switch (this.state.manuallyInstallStatus) {
      case 1:
        installStatusbsStyle = 'info';
        installStatusText = `${__("Installing")}...`;
        break;
      case 2:
        installStatusbsStyle = 'success';
        installStatusText = __("Plugins are installed successfully.");
        break;
      case 3:
        installStatusbsStyle = 'danger';
        installStatusText = __("Install failed. Maybe the selected files are not plugin packages.");
        break;
      default:
        installStatusbsStyle = 'warning';
        installStatusText = '';
    }
    const advanceFAname = this.state.advanced ? 'angle-up' : 'angle-down';
    return _react2.default.createElement(
      'form',
      { className: 'contents-wrapper', style: { marginTop: '10px' } },
      _react2.default.createElement(
        _reactFileDropzone2.default,
        {
          className: 'plugin-dropfile panel',
          onDrop: this.onDropInstallFromFile,
          acceptType: 'application/gzip, application/x-gzip'
        },
        __('Drop plugin tarballs here to install')
      ),
      _react2.default.createElement(
        _reactBootstrap.Grid,
        { className: 'correct-container' },
        _react2.default.createElement(
          _reactBootstrap.Row,
          { className: 'plugin-rowspace' },
          _react2.default.createElement(
            _reactBootstrap.Col,
            { xs: 12 },
            window.isSafeMode && _react2.default.createElement(
              _reactBootstrap.Panel,
              { header: __('Safe Mode'), bsStyle: 'warning' },
              _react2.default.createElement(
                _reactBootstrap.Panel.Body,
                null,
                __('Poi is running in safe mode, plugins are not enabled automatically.')
              )
            ),
            _react2.default.createElement(
              _reactBootstrap.ButtonGroup,
              { bsSize: 'small', className: 'plugin-buttongroup' },
              _react2.default.createElement(
                _reactBootstrap.Button,
                {
                  onClick: this.checkUpdate,
                  disabled: this.state.checkingUpdate,
                  className: 'control-button col-xs-3'
                },
                _react2.default.createElement(_reactFontawesome2.default, { name: 'refresh', spin: this.state.checkingUpdate }),
                _react2.default.createElement(
                  'span',
                  null,
                  ' ',
                  __("Check Update")
                )
              ),
              _react2.default.createElement(
                _reactBootstrap.Button,
                {
                  onClick: this.handleUpdateAll,
                  disabled: this.state.npmWorking || this.state.checkingUpdate || !_pluginManager2.default.getUpdateStatus(),
                  className: 'control-button col-xs-3'
                },
                _react2.default.createElement(_reactFontawesome2.default, {
                  name: updateStatusFAname,
                  pulse: this.state.updatingAll
                }),
                _react2.default.createElement(
                  'span',
                  null,
                  ' ',
                  __("Update all")
                )
              ),
              _react2.default.createElement(
                _reactBootstrap.Button,
                {
                  onClick: this.handleInstallAll,
                  disabled: this.state.npmWorking || Object.keys(uninstalledPluginSettings).length === 0,
                  className: 'control-button col-xs-3'
                },
                _react2.default.createElement(_reactFontawesome2.default, {
                  name: installStatusFAname,
                  pulse: this.state.installingAll
                }),
                _react2.default.createElement(
                  'span',
                  null,
                  ' ',
                  __("Install all")
                )
              ),
              _react2.default.createElement(
                _reactBootstrap.Button,
                {
                  onClick: this.handleAdvancedShow,
                  className: 'control-button col-xs-3'
                },
                _react2.default.createElement(_reactFontawesome2.default, { name: 'gear' }),
                _react2.default.createElement(
                  'span',
                  null,
                  ' ',
                  __("Advanced"),
                  ' '
                ),
                _react2.default.createElement(_reactFontawesome2.default, { name: advanceFAname })
              )
            )
          )
        ),
        _react2.default.createElement(
          _reactBootstrap.Row,
          null,
          _react2.default.createElement(
            _reactBootstrap.Col,
            { xs: 12 },
            _react2.default.createElement(
              _reactBootstrap.Collapse,
              { 'in': this.state.advanced },
              _react2.default.createElement(
                _reactBootstrap.Well,
                null,
                _react2.default.createElement(
                  'div',
                  null,
                  _react2.default.createElement(
                    _reactBootstrap.Row,
                    null,
                    _react2.default.createElement(
                      _reactBootstrap.Col,
                      { xs: 12 },
                      _react2.default.createElement(_checkbox2.default, {
                        label: __('Switch to Plugin Automatically'),
                        configName: 'poi.autoswitch.enabled',
                        defaultVal: true
                      }),
                      _react2.default.createElement(_checkbox2.default, {
                        label: __('Enable autoswitch for main panel'),
                        configName: 'poi.autoswitch.main',
                        defaultVal: true
                      })
                    )
                  ),
                  _react2.default.createElement(
                    _reactBootstrap.Row,
                    null,
                    _react2.default.createElement(
                      _reactBootstrap.Col,
                      { xs: 12 },
                      _react2.default.createElement(
                        _reactBootstrap.Row,
                        null,
                        _react2.default.createElement(
                          _reactBootstrap.Col,
                          { xs: 12 },
                          _react2.default.createElement(
                            'label',
                            { className: 'control-label' },
                            __('Select npm server')
                          )
                        )
                      ),
                      _react2.default.createElement(
                        _reactBootstrap.Row,
                        null,
                        Object.keys(mirrors).map((server, index) => {
                          return _react2.default.createElement(
                            _reactBootstrap.OverlayTrigger,
                            {
                              placement: 'top',
                              key: index,
                              overlay: _react2.default.createElement(
                                _reactBootstrap.Tooltip,
                                { id: `npm-server-${index}` },
                                mirrors[server].menuname
                              )
                            },
                            _react2.default.createElement(
                              _reactBootstrap.Col,
                              { key: index, xs: 6, className: 'select-npm-server' },
                              _react2.default.createElement(
                                _reactBootstrap.Radio,
                                {
                                  checked: this.props.mirrorName == server,
                                  onChange: this.onSelectServer.bind(this, server)
                                },
                                mirrors[server].name
                              )
                            )
                          );
                        }, this)
                      )
                    ),
                    _react2.default.createElement(
                      _reactBootstrap.Col,
                      { xs: 12 },
                      _react2.default.createElement(
                        _reactBootstrap.Row,
                        null,
                        _react2.default.createElement(
                          _reactBootstrap.Col,
                          { xs: 12 },
                          _react2.default.createElement(
                            'label',
                            { className: 'control-label' },
                            __('Others')
                          )
                        )
                      ),
                      _react2.default.createElement(
                        'div',
                        null,
                        _react2.default.createElement(
                          _reactBootstrap.Checkbox,
                          {
                            checked: this.props.proxy || false,
                            onChange: this.handleEnableProxy
                          },
                          __('Connect to npm server through proxy')
                        )
                      ),
                      _react2.default.createElement(
                        'div',
                        null,
                        _react2.default.createElement(
                          _reactBootstrap.Checkbox,
                          {
                            checked: this.props.autoUpdate || false,
                            onChange: this.handleEnableAutoUpdate
                          },
                          __('Automatically update plugins')
                        )
                      ),
                      _react2.default.createElement(
                        'div',
                        null,
                        _react2.default.createElement(
                          _reactBootstrap.Checkbox,
                          {
                            checked: this.props.betaCheck || false,
                            onChange: this.handleEnableBetaPluginCheck
                          },
                          __('Developer option: check update of beta version')
                        )
                      ),
                      _react2.default.createElement(
                        _reactBootstrap.Row,
                        null,
                        _react2.default.createElement(
                          _reactBootstrap.ButtonGroup,
                          { className: 'plugin-buttongroup' },
                          _react2.default.createElement(
                            _reactBootstrap.Button,
                            { className: 'col-xs-4', onClick: this.onSelectOpenFolder },
                            __('Open plugin folder')
                          ),
                          _react2.default.createElement(
                            _reactBootstrap.Button,
                            { className: 'col-xs-4', onClick: this.onSelectOpenSite },
                            __('Search for plugins')
                          ),
                          _react2.default.createElement(
                            _reactBootstrap.Button,
                            { className: 'col-xs-4', onClick: this.handleGracefulRepair },
                            __('Repair plugins')
                          )
                        )
                      )
                    )
                  )
                )
              )
            )
          )
        ),
        _react2.default.createElement(
          _reactBootstrap.Row,
          { className: 'plugin-rowspace' },
          _react2.default.createElement(
            _reactBootstrap.Collapse,
            { 'in': this.state.manuallyInstallStatus > 0 },
            _react2.default.createElement(
              _reactBootstrap.Col,
              { xs: 12 },
              _react2.default.createElement(
                _reactBootstrap.Alert,
                { bsStyle: installStatusbsStyle },
                installStatusText
              )
            )
          )
        ),
        _react2.default.createElement(
          _reactBootstrap.Row,
          { className: 'plugin-rowspace' },
          _react2.default.createElement(
            _reactBootstrap.Col,
            { xs: 12 },
            _react2.default.createElement(_nameInput2.default, {
              handleManuallyInstall: this.handleManuallyInstall,
              manuallyInstallStatus: this.state.manuallyInstallStatus,
              npmWorking: this.state.npmWorking
            })
          ),
          _react2.default.createElement(
            _reactBootstrap.Col,
            { xs: 12 },
            _react2.default.createElement(
              'div',
              { className: 'plugin-dropfile-static', onClick: this.onSelectInstallFromFile },
              __("Drop plugin packages here to install it, or click here to select them")
            )
          )
        ),
        this.props.plugins.map((plugin, index) => {
          return _react2.default.createElement(_installedPlugin2.default, {
            key: plugin.id,
            plugin: plugin,
            handleUpdate: (0, _lodash.partial)(this.handleUpdate, index),
            handleEnable: (0, _lodash.partial)(this.handleEnable, index),
            handleRemove: (0, _lodash.partial)(this.handleRemove, index)
          });
        }, this),
        Object.keys(uninstalledPluginSettings).map((name, index) => {
          const value = uninstalledPluginSettings[name];
          return _react2.default.createElement(_uninstalledPlugin2.default, {
            key: name,
            plugin: value,
            npmWorking: this.state.npmWorking,
            installing: this.state.installingPluginNames.includes(name),
            handleInstall: (0, _lodash.partial)(this.handleInstall, name)
          });
        }, this)
      )
    );
  }
}, _class.propTypes = {
  plugins: _propTypes2.default.array,
  mirrorName: _propTypes2.default.string,
  proxy: _propTypes2.default.bool,
  betaCheck: _propTypes2.default.bool,
  autoUpdate: _propTypes2.default.bool
}, _temp2));

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