import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _objectSpread from "@babel/runtime/helpers/objectSpread";
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";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";

var _dec, _dec2, _class, _class2, _temp;

import React from 'react';
import PropTypes from 'prop-types';
import { Button, Dialog, DialogTitle, GridList, GridListTile, GridListTileBar, Typography, IconButton, withTheme } from '@material-ui/core';
import { Close } from '@material-ui/icons';
import { style } from 'typestyle';
import Dropdown from './Dropdown';
import ImmutableFile from '../../File/ImmutableFile';
import withFiles from '../../store/withFiles';
var configFileName = 'maps.json';
var definitionDir = 'maps/';
var mapNames = Array.from({
  length: 100
}).map(function (_, i) {
  return "map".concat(i + 1);
});
var cn = {
  button: style({
    alignSelf: 'center'
  }),
  dialogClasses: {
    paper: style({
      padding: 4
    })
  },
  title: style({
    display: 'flex',
    alignItems: 'center'
  }),
  blank: style({
    flex: 1
  }),
  tileClasses: {
    root: style({
      height: 'auto'
    }),
    tile: style({
      paddingBottom: '66.6%',
      // responsive embed (3:2)
      height: 0
    })
  },
  img: style({
    top: 0,
    left: 0,
    transform: 'none',
    height: 'auto',
    // GridListTile の自動補正を無効化する
    width: '100%'
  }),
  span: style({
    alignSelf: 'center'
  })
};

var getCn = function getCn(_ref) {
  var theme = _ref.theme;
  return {
    close: style({
      position: 'absolute',
      top: theme.spacing.unit,
      right: theme.spacing.unit
    }),
    confirm: style({
      marginRight: theme.spacing.unit * 2
    }),
    header: style({
      marginLeft: theme.spacing.unit
    })
  };
};

var MapSelector = (_dec = withTheme(), _dec2 = withFiles({
  watch: configFileName
}), _dec(_class = _dec2(_class = (_temp = _class2 =
/*#__PURE__*/
function (_React$Component) {
  _inherits(MapSelector, _React$Component);

  function MapSelector() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, MapSelector);

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

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

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", {
      selected: null,
      // どのマップの背景を変更するか. ボタンが押されたときに Set して, open: Boolean の役割も果たす
      file: null,
      config: {},
      templates: []
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleClick",
    /*#__PURE__*/
    function () {
      var _ref2 = _asyncToGenerator(
      /*#__PURE__*/
      _regeneratorRuntime.mark(function _callee(template) {
        var selected, fileName, definitionFile, config, configFile;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                selected = _this.state.selected;
                _context.next = 3;
                return new Promise(function (resolve) {
                  _this.setState({
                    selected: null
                  }, resolve); // とりあえず閉じる

                });

              case 3:
                if (selected) {
                  _context.next = 5;
                  break;
                }

                return _context.abrupt("return");

              case 5:
                fileName = definitionDir + selected + '.json';
                definitionFile = new ImmutableFile({
                  type: 'application/json',
                  name: fileName,
                  text: template
                });
                config = _objectSpread({}, _this.state.config, {
                  files: _objectSpread({}, _this.state.config.files || {}, _defineProperty({}, selected, fileName))
                });
                configFile = new ImmutableFile({
                  type: 'application/json',
                  name: configFileName,
                  text: JSON.stringify(config, null, 4)
                });

                _this.props.putFiles([definitionFile, configFile]);

                _this.props.setLocation(); // リロード


              case 11:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

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

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleToggle", function () {
      return _this.setState(function (state) {
        return {
          selected: state.selected ? null : _this.props.selected // 開いたときは「今いるマップ」

        };
      });
    });

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

    return _this;
  }

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

      var templateApi = this.state.config && this.state.config.templateApi;

      if (templateApi) {
        getTemplateMaps(templateApi).then(function (templates) {
          _this2.setState({
            templates: templates
          });
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var _this$props = this.props,
          selected = _this$props.selected,
          localization = _this$props.localization;
      var _this$state = this.state,
          file = _this$state.file,
          templates = _this$state.templates;
      if (!selected) return null;
      if (!file) return React.createElement("span", {
        className: cn.span
      }, selected);
      var dcn = getCn(this.props);
      return React.createElement(React.Fragment, null, React.createElement(Button, {
        variant: "contained",
        className: cn.button,
        onClick: this.handleToggle
      }, localization.monitorCard.mapSelector(selected)), React.createElement(Dialog, {
        maxWidth: "md",
        fullWidth: true,
        open: Boolean(this.state.selected),
        classes: cn.dialogClasses,
        onClose: this.handleToggle
      }, React.createElement(DialogTitle, {
        disableTypography: true,
        className: cn.title
      }, React.createElement(Dropdown, {
        items: mapNames,
        selected: this.state.selected || '',
        onSelectChanged: this.handleSelect,
        localization: localization
      }), React.createElement(Typography, {
        variant: "h6",
        className: dcn.header
      }, localization.monitorCard.mapSelectorTitle), React.createElement("div", {
        className: cn.blank
      }), React.createElement(IconButton, {
        onClick: this.handleToggle
      }, React.createElement(Close, null))), React.createElement(GridList, {
        cellHeight: "auto",
        cols: 3
      }, templates.map(function (item, i) {
        return React.createElement(GridListTile, {
          key: i,
          classes: cn.tileClasses
        }, React.createElement("img", {
          src: item.image,
          alt: "",
          className: cn.img
        }), React.createElement(GridListTileBar, {
          title: item.title,
          subtitle: item.createdBy ? React.createElement("span", null, "by: ", item.createdBy) : null,
          actionIcon: React.createElement(Button, {
            variant: "contained",
            color: "primary",
            className: dcn.confirm,
            onClick: function onClick() {
              return _this3.handleClick(item.template);
            }
          }, localization.monitorCard.confirm)
        }));
      }))));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(props, state) {
      var _props$files = _slicedToArray(props.files, 1),
          file = _props$files[0]; // configFile


      if (state.file === file) return null;
      var config = {};

      try {
        config = JSON.parse(file.text);
      } catch (error) {
        console.error(error);
      }

      return {
        file: file,
        config: config
      };
    }
  }]);

  return MapSelector;
}(React.Component), _defineProperty(_class2, "propTypes", {
  selected: PropTypes.string.isRequired,
  setLocation: PropTypes.func.isRequired,
  localization: PropTypes.object.isRequired,
  // Injected by withFiles (for JSX)
  files: PropTypes.array.isRequired,
  putFiles: PropTypes.func.isRequired
}), _defineProperty(_class2, "defaultProps", {
  selected: ''
}), _temp)) || _class) || _class);
export { MapSelector as default };

function getTemplateMaps(_x) {
  return _getTemplateMaps.apply(this, arguments);
}

function _getTemplateMaps() {
  _getTemplateMaps = _asyncToGenerator(
  /*#__PURE__*/
  _regeneratorRuntime.mark(function _callee2(url) {
    var response;
    return _regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.next = 2;
            return fetch(url);

          case 2:
            response = _context2.sent;
            _context2.next = 5;
            return response.json();

          case 5:
            return _context2.abrupt("return", _context2.sent);

          case 6:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, this);
  }));
  return _getTemplateMaps.apply(this, arguments);
}