import _extends from "@babel/runtime/helpers/extends";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
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";

var _dec, _class, _class2, _temp;

import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { style } from 'typestyle';
import Card from '../CardWindow';
import CardContent from '@material-ui/core/CardContent';
import CardActions from '@material-ui/core/CardActions';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import CardFloatingBar from '../CardFloatingBar';
import Readme from './Readme';
import EditFile from '../EditFile';
import shallowEqual from '../../utils/shallowEqual';
import withFiles from '../../store/withFiles';
import normalize from '../../File/normalize';
var cn = {
  text: style({
    flex: 1,
    paddingTop: 0,
    overflowX: 'hidden',
    overflowY: 'scroll'
  })
};
var ReadmeCard = (_dec = withFiles({
  watch: '**/*.md'
}), _dec(_class = (_temp = _class2 =
/*#__PURE__*/
function (_PureComponent) {
  _inherits(ReadmeCard, _PureComponent);

  function ReadmeCard() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, ReadmeCard);

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

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

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", {
      selected: null,
      // file name
      completes: []
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleComplete", function (event) {
      var value = event.data.value;

      if (!shallowEqual(value, _this.state.completes)) {
        _this.setState({
          completes: value
        });
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleReadme", function (event) {
      var value = event.data.value;

      if (value) {
        // feeles.openReamde()
        var filePath = normalize(value);

        var selectedFile = _this.props.files.find(function (file) {
          return file.name === filePath;
        });

        if (!selectedFile) {
          throw new Error("Not Found Error: feeles.openReamde(\"".concat(value, "\")"));
        }

        _this.setState({
          selected: selectedFile.name
        });

        _this.props.setCardVisibility('ReadmeCard', true);
      } else {
        // feeles.closeReadme()
        _this.props.setCardVisibility('ReadmeCard', false);
      }
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleSelect", function (event) {
      _this.setState({
        selected: event.target.value
      });
    });

    return _this;
  }

  _createClass(ReadmeCard, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var globalEvent = this.props.globalEvent;
      globalEvent.on('message.complete', this.handleComplete);
      globalEvent.on('message.readme', this.handleReadme);
    }
  }, {
    key: "renderDropDownMenu",
    value: function renderDropDownMenu() {
      var localization = this.props.localization;
      var selected = this.state.selected;

      var markdowns = _toConsumableArray(this.props.files).sort(function (a, b) {
        return extractMarkdownHeader(a) > extractMarkdownHeader(b) ? 1 : -1;
      });

      var styles = {
        index: {
          marginLeft: 16,
          fontSize: '.5rem'
        },
        dropDown: {
          verticalAlign: 'bottom'
        }
      };
      return [React.createElement("span", {
        key: "index",
        className: styles.index
      }, localization.readmeCard.index), React.createElement(Select, {
        key: "dropDown",
        value: selected,
        className: styles.dropDown,
        onChange: this.handleSelect
      }, markdowns.map(function (file) {
        return React.createElement(MenuItem, {
          key: file.name,
          value: file.name
        }, extractMarkdownHeader(file));
      }))];
    }
  }, {
    key: "render",
    value: function render() {
      var localization = this.props.localization;
      var selected = this.state.selected;
      var file = this.props.files.find(function (file) {
        return file.name === selected;
      });
      if (!file) return null;
      return React.createElement(Card, _extends({}, this.props.cardPropsBag, {
        fit: true
      }), React.createElement(CardFloatingBar, null, this.props.localization.readmeCard.title), React.createElement(CardContent, {
        className: cn.text
      }, React.createElement(Readme, {
        file: file,
        localization: this.props.localization,
        completes: this.state.completes,
        setLocation: this.props.setLocation,
        globalEvent: this.props.globalEvent
      })), React.createElement(CardActions, null, this.renderDropDownMenu(), React.createElement(EditFile, {
        filePath: file.name,
        globalEvent: this.props.globalEvent,
        localization: localization
      })));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      if (!prevState.selected) {
        try {
          var init = nextProps.cardProps.ReadmeCard.init;
          var selected = init && init.fileName;

          if (selected) {
            return {
              selected: selected
            };
          }
        } catch (error) {// nope
        }
      }

      return null;
    }
  }]);

  return ReadmeCard;
}(PureComponent), _defineProperty(_class2, "propTypes", {
  cardPropsBag: PropTypes.object.isRequired,
  localization: PropTypes.object.isRequired,
  setLocation: PropTypes.func.isRequired,
  setCardVisibility: PropTypes.func.isRequired,
  cardProps: PropTypes.object.isRequired,
  globalEvent: PropTypes.object.isRequired,
  // Injected by withFiles (for JSX)
  files: PropTypes.array.isRequired
}), _temp)) || _class);
export { ReadmeCard as default };

function extractMarkdownHeader(file) {
  return file.text.trim() // 前後の空白を削除
  .replace(/\n[^]*$/, '') // 改行以降を削除
  .trim() // 前後の空白を削除
  .replace(/^[#-]*\s*/, '') // 行頭の # - を削除
  .replace(/[*~_[\]()`]/g, ''); // * ~ _ [] () `` を削除
}