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";

var _dec, _dec2, _class, _class2, _temp;

import Button from '@material-ui/core/Button';
import ButtonBase from '@material-ui/core/ButtonBase';
import Popover from '@material-ui/core/Popover';
import { withTheme } from '@material-ui/core/styles';
import { fade } from '@material-ui/core/styles/colorManipulator';
import Typography from '@material-ui/core/Typography';
import Add from '@material-ui/icons/Add';
import { url } from 'csx';
import { debounce } from 'lodash';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import { classes, style } from 'typestyle';
import withAsset from '../../store/withAsset';
import Dropdown from '../MonitorCard/Dropdown';
import { pathToInstall } from './AssetPane';
var iconSize = 48;
var cn = {
  mainButton: style({
    width: 80,
    height: 80,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'stretch'
  }),
  mainIcon: style({
    flex: 1,
    backgroundSize: 'contain',
    backgroundPosition: '50% 50%',
    backgroundRepeat: 'no-repeat'
  }),
  popoverClasses: {
    paper: style({
      padding: 8,
      maxWidth: 500
    })
  },
  label: style({
    fontSize: 10,
    fontWeight: 600
  }),
  variationWrapper: style({
    display: 'flex',
    flexWrap: 'nowrap',
    justifyContent: 'flex-start'
  }),
  scopeDropdownWrapper: style({
    marginBottom: 8
  })
};

var getCn = function getCn(_ref) {
  var theme = _ref.theme;
  return {
    root: style({
      position: 'relative',
      margin: '8px 8px 0px 8px'
    }),
    button: style({
      color: theme.palette.getContrastText(theme.palette.text.primary),
      transition: theme.transitions.create('background-color'),
      backgroundColor: fade(theme.palette.grey[600], 0.6),
      $nest: {
        '&:hover': {
          backgroundColor: theme.palette.grey[600]
        },
        '&:disabled': {
          color: theme.palette.text.disabled
        }
      }
    }),
    variation: style({
      maxWidth: iconSize,
      height: iconSize,
      boxSizing: 'content-box',
      borderStyle: 'solid',
      borderWidth: 2,
      borderColor: 'transparent',
      borderRadius: theme.shape.borderRadius,
      marginRight: theme.spacing.unit,
      marginBottom: theme.spacing.unit,
      $nest: {
        '&>img': {
          maxWidth: iconSize,
          height: iconSize
        }
      }
    }),
    variationEnabled: style({
      backgroundColor: theme.palette.grey[200],
      cursor: 'pointer',
      $nest: {
        '&:hover': {
          backgroundColor: theme.palette.grey[400]
        }
      }
    }),
    variationDisabled: style({
      backgroundColor: theme.palette.grey[100],
      pointerEvents: 'none'
    }),
    selected: style({
      borderColor: '#4A90E2',
      backgroundColor: theme.palette.grey[400]
    })
  };
};

var AssetButton = (_dec = withTheme(), _dec2 = withAsset({}), _dec(_class = _dec2(_class = (_temp = _class2 =
/*#__PURE__*/
function (_PureComponent) {
  _inherits(AssetButton, _PureComponent);

  function AssetButton() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, AssetButton);

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

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

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "state", {
      anchorEl: null,
      backgroundStyle: {},
      selectedIndex: 0,
      // 選択中の variation
      selectedScope: '' // スコープ Dropdown の選択情報

    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "scopeIndexToName", function () {
      var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
      var scope = _this.props.asset.assetPackage.scopes && _this.props.asset.assetPackage.scopes[index];
      return scope && scope.name;
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleOpen", function (event) {
      _this.setState({
        anchorEl: event.currentTarget
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleClose", function () {
      _this.setState({
        anchorEl: null
      });
    });

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleInsertAssetSelected", debounce(function () {
      _this.handleClose();

      _this.props.insertAsset(_this.selected, _this.state.selectedScope);
    }, 5000, {
      leading: true,
      trailing: false
    }));

    _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "handleOpenFile", debounce(function () {
      _this.handleClose();

      _this.props.openFile({
        name: _this.props.name,
        filePath: _this.filePathToOpen,
        iconUrl: _this.props.iconUrl
      });
    }, 5000, {
      leading: true,
      trailing: false
    }));

    return _this;
  }

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

      var dcn = getCn(this.props);
      var _this$props = this.props,
          localization = _this$props.localization,
          variations = _this$props.variations,
          canUseAssetButton = _this$props.canUseAssetButton;
      var selectedIndex = this.state.selectedIndex;
      var selected = this.selected; // Popover の中は選択中のバリエーションに切り替わる

      return React.createElement(React.Fragment, null, React.createElement("div", {
        className: dcn.root
      }, React.createElement(ButtonBase, {
        focusRipple: true,
        className: classes(dcn.button, cn.mainButton),
        onClick: this.handleOpen
      }, React.createElement("div", {
        className: cn.mainIcon,
        style: this.state.backgroundStyle
      }), React.createElement("span", {
        className: cn.label
      }, this.props.name))), React.createElement(Popover, {
        open: Boolean(this.state.anchorEl),
        anchorOrigin: {
          vertical: 'bottom',
          horizontal: 'left'
        },
        anchorEl: this.state.anchorEl,
        classes: cn.popoverClasses,
        onClose: this.handleClose
      }, React.createElement(Typography, {
        variant: "h5"
      }, selected.name), React.createElement(Typography, {
        variant: "body1",
        gutterBottom: true
      }, selected.description), variations && React.createElement("div", {
        className: cn.variationWrapper
      }, variations.map(function (child, i) {
        return React.createElement("div", {
          key: i,
          className: classes(dcn.variation, selectedIndex === i && dcn.selected, canUseAssetButton(child) ? dcn.variationEnabled : dcn.variationDisabled),
          onClick: function onClick() {
            return _this2.setState({
              selectedIndex: i
            });
          }
        }, React.createElement("img", {
          src: child.iconUrl,
          alt: child.name
        }));
      })), selected.scopes ? React.createElement("div", {
        className: cn.scopeDropdownWrapper
      }, React.createElement(Dropdown, {
        items: selected.scopes.map(this.scopeIndexToName).filter(this.props.isAvailableScope),
        selected: this.state.selectedScope,
        onSelectChanged: function onSelectChanged(selectedScope) {
          return _this2.setState({
            selectedScope: selectedScope
          });
        },
        localization: localization
      })) : null, React.createElement("div", null, React.createElement(Button, {
        variant: "contained",
        color: "primary",
        disabled: !selected.insertCode || !this.state.selectedScope,
        onClick: this.handleInsertAssetSelected
      }, React.createElement(Add, null), localization.editorCard.insert))));
    }
  }, {
    key: "selected",
    get: function get() {
      var _this$props2 = this.props,
          name = _this$props2.name,
          description = _this$props2.description,
          iconUrl = _this$props2.iconUrl,
          insertCode = _this$props2.insertCode,
          moduleCode = _this$props2.moduleCode,
          filePath = _this$props2.filePath,
          variations = _this$props2.variations,
          scopes = _this$props2.scopes;
      return variations ? variations[this.state.selectedIndex] : {
        name: name,
        description: description,
        iconUrl: iconUrl,
        insertCode: insertCode,
        moduleCode: moduleCode,
        filePath: filePath,
        scopes: scopes
      };
    }
  }, {
    key: "filePathToOpen",
    get: function get() {
      // 最初から存在するファイルにアクセス => filePath
      // 追加してからアクセス => asset.assetPackage.module[name]
      var _this$props3 = this.props,
          filePath = _this$props3.filePath,
          asset = _this$props3.asset,
          name = _this$props3.name;
      return filePath || (asset.assetPackage.module[name] ? "".concat(pathToInstall, "/").concat(name, ".js") : null);
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(props, state) {
      var nextState = null;

      if (props.iconUrl) {
        var backgroundImage = url(props.iconUrl);

        if (backgroundImage && backgroundImage !== state.backgroundStyle.backgroundImage) {
          nextState = {
            backgroundStyle: {
              backgroundImage: backgroundImage
            }
          };
        }
      }

      if (!state.selectedScope && props.defaultScope) {
        nextState = _objectSpread({}, nextState || {}, {
          selectedScope: props.defaultScope
        });
      }

      return nextState;
    }
  }]);

  return AssetButton;
}(PureComponent), _defineProperty(_class2, "propTypes", {
  name: PropTypes.string,
  description: PropTypes.string,
  iconUrl: PropTypes.string,
  insertCode: PropTypes.string,
  moduleCode: PropTypes.string,
  filePath: PropTypes.string,
  variations: PropTypes.array,
  scopes: PropTypes.array,
  theme: PropTypes.object.isRequired,
  insertAsset: PropTypes.func.isRequired,
  openFile: PropTypes.func.isRequired,
  localization: PropTypes.object.isRequired,
  globalEvent: PropTypes.object.isRequired,
  isAvailableScope: PropTypes.func.isRequired,
  defaultScope: PropTypes.string.isRequired,
  // Injected by withAsset
  canUseAssetButton: PropTypes.func.isRequired,
  asset: PropTypes.object.isRequired
}), _defineProperty(_class2, "defaultProps", {
  name: '',
  description: ''
}), _temp)) || _class) || _class);
export { AssetButton as default };