'use strict';

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

var _class, _temp2;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _reselect = require('reselect');

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

var _lodash = require('lodash');

var _icon = require('views/components/etc/icon');

var _selectors = require('views/utils/selectors');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const { i18n, toast, config } = window;
const __ = i18n.others.__.bind(i18n.others);
const emptyObj = {};

const MapRoutes = (0, _reactRedux.connect)(state => ({
  sortieMapId: (0, _lodash.get)(state, 'sortie.sortieMapId'),
  spotHistory: (0, _lodash.get)(state, 'sortie.spotHistory'),
  bossSpot: (0, _lodash.get)(state, 'sortie.bossSpot'),
  allMaps: (0, _lodash.get)(state, 'fcd.map')
}))(({ sortieMapId, spotHistory, bossSpot, allMaps }) => {
  if (!sortieMapId || !allMaps) return _react2.default.createElement('div', null);
  const mapspots = (0, _lodash.get)(allMaps, `${Math.floor(sortieMapId / 10)}-${sortieMapId % 10}.spots`, {});
  if (!mapspots || !Object.keys(mapspots).length) return _react2.default.createElement('div', null);
  const maproutes = (0, _lodash.get)(allMaps, `${Math.floor(sortieMapId / 10)}-${sortieMapId % 10}.route`, {});
  const histLen = spotHistory.length;
  const activeSpot = spotHistory[histLen - 1];
  const bossSpotLoc = mapspots[(0, _lodash.get)(maproutes, `${bossSpot}.1`)] || [-100, -100];
  const locHistory = spotHistory.map(i => mapspots[(0, _lodash.get)(maproutes, `${i}.1`)] || [-1, -1]);
  const lineHistory = histLen ? (0, _lodash.zip)(locHistory.slice(0, histLen - 1), locHistory.slice(1)) : [[-1, -1], [-1, -1]];
  return _react2.default.createElement(
    'div',
    null,
    _react2.default.createElement(
      'svg',
      { width: '225', height: '120', viewBox: '0 0 225 120', className: 'maproutes' },
      // Draw all lines
      (0, _lodash.map)(maproutes, ([beg, end], i) => {
        if (!(mapspots[beg] && mapspots[end])) return null;
        const [begX, begY] = mapspots[beg];
        const [endX, endY] = mapspots[end];
        return _react2.default.createElement('line', { key: i, x1: parseInt(begX / 200 * 3), y1: parseInt(begY / 200 * 3), x2: parseInt(endX / 200 * 3), y2: parseInt(endY / 200 * 3) });
      }),
      // Draw passed lines
      lineHistory.map(([[begX, begY], [endX, endY]], i) => begX > 0 && endX > 0 ? _react2.default.createElement('line', { key: i, x1: parseInt(begX / 200 * 3), y1: parseInt(begY / 200 * 3), x2: parseInt(endX / 200 * 3), y2: parseInt(endY / 200 * 3), className: 'passed' }) : _react2.default.createElement('noscript', null)),
      _react2.default.createElement('rect', { x: parseInt(bossSpotLoc[0] / 200 * 3) - 4.5, y: parseInt(bossSpotLoc[1] / 200 * 3) - 4.5, width: 9, height: 9,
        className: 'boss' }),
      // Draw all points
      (0, _lodash.map)(mapspots, ([x, y], id) => _react2.default.createElement('rect', { key: id, x: parseInt(x / 200 * 3) - 3, y: parseInt(y / 200 * 3) - 3, width: 6, height: 6 })),
      // Draw passed points again, highlighting the active one
      (0, _lodash.map)((0, _lodash.zip)(spotHistory, locHistory), ([id, [x, y]]) => x > 0 ? _react2.default.createElement('rect', { key: id, x: parseInt(x / 200 * 3) - 3, y: parseInt(y / 200 * 3) - 3, width: 6, height: 6,
        className: id == activeSpot ? 'active' : 'passed' }) : _react2.default.createElement('noscript', null))
    )
  );
});

const ItemStat = (0, _reactRedux.connect)(state => ({
  itemHistoty: (0, _lodash.get)(state, 'sortie.itemHistory')
}))(({ itemHistoty }) => {
  const stat = {};
  (0, _lodash.each)(itemHistoty, (item = {}) => {
    (0, _lodash.each)(Object.keys(item), itemKey => stat[itemKey] = item[itemKey] + (stat[itemKey] || 0));
  });
  return _react2.default.createElement(
    'div',
    null,
    Object.keys(stat).length > 0 && __('Resources: '),
    (0, _lodash.map)(Object.keys(stat), itemKey => itemKey && _react2.default.createElement(
      'span',
      { key: itemKey, className: 'item-stat' },
      _react2.default.createElement(_icon.MaterialIcon, { materialId: parseInt(itemKey), className: 'material-icon reminder' }),
      stat[itemKey] > 0 ? `+${stat[itemKey]}` : String(stat[itemKey])
    ))
  );
}

// Map Reminder
);exports.default = (0, _reactRedux.connect)((0, _reselect.createSelector)([_selectors.sortieMapDataSelector, _selectors.sortieMapHpSelector, _selectors.currentNodeSelector, _selectors.fcdSelector], (mapData, mapHp, currentNode, fcd = {}) => ({
  mapId: (0, _lodash.get)(mapData, '0.api_id'),
  rank: (0, _lodash.get)(mapData, '0.api_eventmap.api_selected_rank'),
  currentNode,
  mapData,
  mapHp,
  finalHps: fcd.maphp || emptyObj,
  maps: fcd.map || emptyObj
})))((_temp2 = _class = class MapReminder extends _react.Component {
  constructor(...args) {
    var _temp;

    return _temp = super(...args), this.isFinalAttack = () => {
      const { mapHp, rank, mapId } = this.props;
      if (!mapHp || mapHp[0] == 0) return false;
      const finalHpPostfix = ['', '丙', '乙', '甲'][rank] || '';
      const finalHp = this.props.finalHps[`${mapId}${finalHpPostfix}`] || 0;
      return finalHp >= mapHp[0];
    }, this.notifyFinalAttack = e => {
      if (e.detail.path === '/kcsapi/api_req_map/start') {
        const isFinalAttack = this.isFinalAttack();
        if (isFinalAttack && config.get("poi.lastbattle.enabled", true)) {
          toast(__('Possible final stage'), {
            type: 'warning',
            title: __('Sortie')
          });
        }
      }
    }, _temp;
  }

  getMapText(mapData) {
    if (!mapData) return __('Not in sortie');
    const { rank } = this.props;
    const { api_maparea_id, api_no } = mapData[1];

    const mapName = `${api_maparea_id}-${api_no}` + (rank == null ? '' : this.constructor.mapRanks[rank]);
    return `${__('Sortie area: ')}${mapName}`;
  }

  componentDidMount() {
    window.addEventListener('game.response', this.notifyFinalAttack);
  }

  componentWillUnmount() {
    window.removeEventListener('game.response', this.notifyFinalAttack);
  }

  render() {
    const { mapHp, mapData, currentNode, mapId, maps } = this.props;
    const tooltipMsg = [];
    const alphaNode = (0, _lodash.get)(maps, `${Math.floor(mapId / 10)}-${mapId % 10}.route.${currentNode}.1`) || '?';
    if (currentNode) {
      tooltipMsg.push(`${__('Node: ')}${alphaNode} (${currentNode})`);
    }
    if (mapHp && mapHp[1] > 0 && mapHp[0] !== 0) {
      tooltipMsg.push(`HP: ${mapHp[0]} / ${mapHp[1]}`);
    }
    return _react2.default.createElement(
      _reactBootstrap.OverlayTrigger,
      {
        placement: 'top',
        overlay: _react2.default.createElement(
          _reactBootstrap.Tooltip,
          { id: 'detail-map-info', className: 'reminder-pop', style: tooltipMsg.length === 0 ? { display: 'none' } : {} },
          _react2.default.createElement(MapRoutes, null),
          _react2.default.createElement(
            'div',
            null,
            tooltipMsg.join('  |  ')
          ),
          _react2.default.createElement(ItemStat, null)
        ) },
      _react2.default.createElement(
        'div',
        null,
        !mapHp ? undefined : _react2.default.createElement(_reactBootstrap.ProgressBar, { bsStyle: 'info', now: mapHp[0], max: mapHp[1] }),
        _react2.default.createElement(
          'div',
          { className: 'alert alert-default' },
          _react2.default.createElement(
            'span',
            { id: 'map-reminder-area' },
            this.getMapText(mapData)
          )
        )
      )
    );
  }
}, _class.mapRanks = ['', ` ${__('丙')}`, ` ${__('乙')}`, ` ${__('甲')}`], _temp2));
module.exports = exports['default'];