import _extends from "@babel/runtime/helpers/extends";
import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/inherits";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";

var _dec, _dec2, _class, _class2, _temp;

import React, { PureComponent } from 'react';
import { withTheme } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import { style } from 'typestyle';
import Button from '@material-ui/core/Button';
import AVPlayCircleOutline from '@material-ui/icons/PlayCircleOutline';
import Card from '../CardWindow';
import SourceEditor from './SourceEditor';
import withFiles from '../../store/withFiles';
var cn = {
  largeIcon: style({
    width: 40,
    height: 40
  }),
  large: style({
    width: 80,
    height: 80,
    padding: 20
  })
};

var getCn = function getCn(props) {
  return {
    noFileBg: style({
      flex: '1 1 auto',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: props.theme.palette.primary.main
    })
  };
};

export var Tab =
/*#__PURE__*/
function () {
  function Tab(_ref) {
    var label = _ref.label,
        filePath = _ref.filePath,
        iconUrl = _ref.iconUrl,
        tabs = _ref.tabs;

    _classCallCheck(this, Tab);

    this.label = label;
    this.iconUrl = iconUrl;

    if (filePath) {
      this.filePath = filePath;
    } else if (tabs) {
      this.tabs = tabs.map(function (props) {
        return new Tab(props);
      });
    }
  }

  _createClass(Tab, null, [{
    key: "find",
    value: function find(tabs, filePath) {
      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = tabs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var tab = _step.value;
          if (tab.filePath === filePath) return tab;
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator.return != null) {
            _iterator.return();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }

      var _iteratorNormalCompletion2 = true;
      var _didIteratorError2 = false;
      var _iteratorError2 = undefined;

      try {
        for (var _iterator2 = tabs[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
          var _tab = _step2.value;

          if (Array.isArray(_tab.tabs)) {
            var found = Tab.find(_tab.tabs, filePath);
            if (found) return found;
          }
        }
      } catch (err) {
        _didIteratorError2 = true;
        _iteratorError2 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
            _iterator2.return();
          }
        } finally {
          if (_didIteratorError2) {
            throw _iteratorError2;
          }
        }
      }
    }
  }]);

  return Tab;
}();
var EditorCard = (_dec = withTheme(), _dec2 = withFiles({}), _dec(_class = _dec2(_class = (_temp = _class2 =
/*#__PURE__*/
function (_PureComponent) {
  _inherits(EditorCard, _PureComponent);

  function EditorCard() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, EditorCard);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(EditorCard)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", {
      filePath: '',
      // 現在開いているファイルの名前. 空文字の場合は何も開いていない
      tabs: [],
      // プルダウンメニューの中で表示するファイルのリスト
      label: '',
      // このファイルの呼び名（アセットから取得する）
      iconUrl: '',
      // このファイルのアイコン（アセットから取得する）
      filePathToBack: '' // 最初に表示するファイルのパス. ホーム

    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "openFile", function (filePath) {
      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      if (!filePath || filePath === _this.state.filePath) return;

      var file = _this.props.files.find(function (f) {
        return f.name === filePath;
      }); // file type を知るために探す


      if (!file) return; // ファイルが見つからなかった

      if (file.is('text')) {
        // テキストの場合は EditorCard で open
        var tabs = _this.state.tabs;
        var existTab = Tab.find(tabs, filePath);

        if (!existTab) {
          // 開こうとしているファイルを tabs の先頭に追加
          var tab = new Tab({
            filePath: filePath,
            label: file.plain + file.ext
          });
          tabs = [tab].concat(tabs);
        }

        _this.setState({
          filePath: filePath,
          tabs: tabs,
          label: options.label ? options.label + '' : existTab ? existTab.label : file.plain,
          iconUrl: options.iconUrl || ''
        });

        _this.props.setCardVisibility('EditorCard', true); // タブの選択が変化したら EditorCard にスクロールする


        _this.props.scrollToCard('EditorCard');
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "setLocation", function (href) {
      _this.props.setLocation(href);

      _this.props.scrollToCard('MonitorCard');
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleEditor", function (event) {
      var _event$data = event.data,
          value = _event$data.value,
          options = _event$data.options;

      if (value) {
        // feeles.openEditor()
        _this.openFile(value, options);
      } else {
        // feeles.closeEditor()
        _this.props.setCardVisibility('EditorCard', false);
      }
    });

    return _this;
  }

  _createClass(EditorCard, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;

      var globalEvent = this.props.globalEvent;
      globalEvent.on('message.editor', this.handleEditor); // init.fileName があるとき Mount 後に開いておく

      try {
        var init = this.props.cardProps.EditorCard.init;

        if (init) {
          new Promise(function (resolve) {
            if (Array.isArray(init.tabs)) {
              var tabs = init.tabs.map(function (seed) {
                return new Tab(seed);
              });

              _this2.setState({
                tabs: tabs
              }, resolve);
            } else {
              resolve();
            }
          }).then(function () {
            var filePath = init.filePath || init.fileName; // 後方互換性

            _this2.setState({
              filePathToBack: filePath
            }); // ホームに設定


            _this2.openFile(filePath);
          });
        }
      } catch (e) {// continue regardless of error
      }
    }
  }, {
    key: "renderBackground",
    value: function renderBackground(className) {
      var _this3 = this;

      return React.createElement("div", {
        className: className
      }, React.createElement(Button, {
        variant: "contained",
        size: "large",
        onClick: function onClick() {
          return _this3.setLocation();
        }
      }, "Feeles", React.createElement(AVPlayCircleOutline, {
        className: cn.largeIcon
      })));
    }
  }, {
    key: "render",
    value: function render() {
      var filePath = this.state.filePath;
      var dcn = getCn(this.props);

      if (!filePath) {
        return React.createElement(Card, _extends({}, this.props.cardPropsBag, {
          fit: true
        }), this.renderBackground(dcn.noFileBg));
      }

      var _this$props = this.props,
          openFileDialog = _this$props.openFileDialog,
          localization = _this$props.localization,
          getConfig = _this$props.getConfig,
          reboot = _this$props.reboot,
          cardPropsBag = _this$props.cardPropsBag;
      return React.createElement(Card, _extends({}, cardPropsBag, {
        fit: true,
        flexBasis: this.props.isExpandingEditorCard ? '75%' : '50%'
      }), React.createElement(SourceEditor, {
        filePath: filePath,
        setLocation: this.setLocation,
        href: this.props.href,
        getConfig: getConfig,
        loadConfig: this.props.loadConfig,
        localization: localization,
        reboot: reboot,
        openFileDialog: openFileDialog,
        tabs: this.state.tabs,
        label: this.state.label,
        iconUrl: this.state.iconUrl,
        filePathToBack: this.state.filePathToBack,
        globalEvent: this.props.globalEvent,
        isExpandingEditorCard: this.props.isExpandingEditorCard,
        setExpandingEditorCard: this.props.setExpandingEditorCard
      }));
    }
  }]);

  return EditorCard;
}(PureComponent), _defineProperty(_class2, "propTypes", {
  theme: PropTypes.object.isRequired,
  cardPropsBag: PropTypes.object.isRequired,
  setLocation: PropTypes.func.isRequired,
  openFileDialog: PropTypes.func.isRequired,
  localization: PropTypes.object.isRequired,
  getConfig: PropTypes.func.isRequired,
  loadConfig: PropTypes.func.isRequired,
  reboot: PropTypes.bool.isRequired,
  href: PropTypes.string.isRequired,
  scrollToCard: PropTypes.func.isRequired,
  cardProps: PropTypes.object.isRequired,
  setCardVisibility: PropTypes.func.isRequired,
  globalEvent: PropTypes.object.isRequired,
  isExpandingEditorCard: PropTypes.bool.isRequired,
  setExpandingEditorCard: PropTypes.func.isRequired,
  // Injected by withFiles (for JSX)
  files: PropTypes.array.isRequired
}), _temp)) || _class) || _class);
export { EditorCard as default };
export { default as SourceEditor } from './SourceEditor';