'use strict';

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

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

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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reselect = require('reselect');

var _lodash = require('lodash');

var _momentTimezone = require('moment-timezone');

var _momentTimezone2 = _interopRequireDefault(_momentTimezone);

var _reactFontawesome = require('react-fontawesome');

var _reactFontawesome2 = _interopRequireDefault(_reactFontawesome);

var _countdownTimer = require('views/components/main/parts/countdown-timer');

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

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

const { i18n } = window;
const __ = i18n.main.__.bind(i18n.main);

const rankName = ['', '元帥', '大将', '中将', '少将', '大佐', '中佐', '新米中佐', '少佐', '中堅少佐', '新米少佐'];

const totalExp = [0, 100, 300, 600, 1000, 1500, 2100, 2800, 3600, 4500, 5500, 6600, 7800, 9100, 10500, 12000, 13600, 15300, 17100, 19000, 21000, 23100, 25300, 27600, 30000, 32500, 35100, 37800, 40600, 43500, 46500, 49600, 52800, 56100, 59500, 63000, 66600, 70300, 74100, 78000, 82000, 86100, 90300, 94600, 99000, 103500, 108100, 112800, 117600, 122500, 127500, 132700, 138100, 143700, 149500, 155500, 161700, 168100, 174700, 181500, 188500, 195800, 203400, 211300, 219500, 228000, 236800, 245900, 255300, 265000, 275000, 285400, 296200, 307400, 319000, 331000, 343400, 356200, 369400, 383000, 397000, 411500, 426500, 442000, 458000, 474500, 491500, 509000, 527000, 545500, 564500, 584500, 606500, 631500, 661500, 701500, 761500, 851500, 1000000, 1300000, 1600000, 1900000, 2200000, 2600000, 3000000, 3500000, 4000000, 4600000, 5200000, 5900000, 6600000, 7400000, 8200000, 9100000, 10000000, 11000000, 12000000, 13000000, 14000000, 15000000];

const resolveDayTime = time => {
  const seconds = parseInt(time);
  if (seconds >= 0) {
    const s = seconds % 60;
    const m = Math.trunc(seconds / 60) % 60;
    const h = Math.trunc(seconds / 3600) % 24;
    const d = Math.trunc(seconds / 86400);
    return [d ? `${d}${__('d')}` : '', h ? `${h}${__('h')}` : '', m ? `${m}${__('m')}` : '', s ? `${s}${__('s')}` : ''].join(' ');
  } else {
    return '';
  }
};

const getLabelStyle = (_, timeRemaining) => {
  switch (true) {
    case timeRemaining > 1800:
      return 'default';
    case timeRemaining > 900:
      return 'warning';
    default:
      return 'danger';
  }
};

const ExpContent = (0, _reactRedux.connect)(state => ({
  level: (0, _lodash.get)(state, 'info.basic.api_level', 0),
  exp: (0, _lodash.get)(state, 'info.basic.api_experience', 0)
}))(({ level, exp }) => _react2.default.createElement(
  'div',
  null,
  level < 120 && _react2.default.createElement(
    'div',
    { className: 'info-tooltip-entry' },
    _react2.default.createElement(
      'span',
      { className: 'info-tooltip-item' },
      __('Next')
    ),
    _react2.default.createElement(
      'span',
      null,
      totalExp[level] - exp
    )
  ),
  _react2.default.createElement(
    'div',
    { className: 'info-tooltip-entry' },
    _react2.default.createElement(
      'span',
      { className: 'info-tooltip-item' },
      __('Total Exp.')
    ),
    _react2.default.createElement(
      'span',
      null,
      exp
    )
  )
)

// Refresh time:
// - Practice: JST 3h00, 15h00, UTC 18h00, 6h00
// - Quest: JST 5h00, UTC 20h00
// - Senka: JST 22h00 on last day of every month, UTC 13h00
// - Extra Operation: JST 0h00 on first day of every month, UTC 15h00 on last day of every month

);const getNextPractice = () => {
  const now = _momentTimezone2.default.utc();
  const nowHour = now.hour();
  if (nowHour < 6) {
    now.hour(6);
  } else if (nowHour < 18) {
    now.hour(18);
  } else {
    now.hour(30);
  }
  return now.startOf('hour');
};

const getNextQuest = () => {
  const now = _momentTimezone2.default.utc();
  const nowHour = now.hour();
  if (nowHour < 20) {
    now.hour(20);
  } else {
    now.hour(44);
  }
  return now.startOf('hour');
};

const getNextSenka = () => {
  const now = _momentTimezone2.default.utc();
  const nowDate = now.date();
  const nowHour = now.hour();
  const currentMonth = _momentTimezone2.default.tz('Asia/Tokyo').month();
  const endOfMonth = _momentTimezone2.default.utc().month(currentMonth).endOf('month');
  if (endOfMonth.date() === nowDate && nowHour >= 13 && nowHour < 15) {
    return endOfMonth.subtract(11, 'hours').add(1, 'months');
  }
  return endOfMonth.subtract(11, 'hours');
};

const getNextEO = () => {
  const currentMonth = _momentTimezone2.default.tz('Asia/Tokyo').month();
  const endOfMonth = _momentTimezone2.default.utc().month(currentMonth).endOf('month');
  return endOfMonth.subtract(9, 'hours');
};

const getNewMomentMap = {
  Practice: getNextPractice,
  Quest: getNextQuest,
  Senka: getNextSenka,
  EO: getNextEO
};

class CountDownControl extends _react.Component {
  constructor(props) {
    super(props);

    this.componentDidMount = () => {
      this.startTick();
      window.addEventListener('countdown.start', this.startTick);
      window.addEventListener('countdown.stop', this.stopTick);
    };

    this.componentWillUnmount = () => {
      this.stopTick();
      window.removeEventListener('countdown.start', this.startTick);
      window.removeEventListener('countdown.stop', this.stopTick);
    };

    this.startTick = () => {
      window.ticker.reg('admiral-panel', this.tick);
    };

    this.stopTick = () => {
      window.ticker.unreg('admiral-panel');
    };

    this.tick = currentTime => {
      // update moments
      Object.keys(this.moments).forEach(key => {
        if (this.moments[key] - currentTime < 0) {
          this.moments[key] = getNewMomentMap[key]();
        }
      }

      // check styles
      );const minRemaining = Math.min(...(0, _lodash.map)(this.moments, moment => moment - currentTime));
      const style = getLabelStyle(null, minRemaining / 1000);

      if (style !== this.state.style) {
        this.setState({
          style
        });
      }
    };

    this.moments = {
      Practice: getNextPractice(),
      Quest: getNextQuest(),
      Senka: getNextSenka(),
      EO: getNextEO()
    };
    this.state = {
      style: 'default'
    };
  }

  render() {
    const { style } = this.state;
    return _react2.default.createElement(
      'span',
      null,
      _react2.default.createElement(
        _reactBootstrap.OverlayTrigger,
        {
          placement: 'bottom',
          overlay: _react2.default.createElement(
            _reactBootstrap.Tooltip,
            { id: 'next-time', className: 'info-tooltip' },
            _react2.default.createElement(CountdownContent, { moments: this.moments })
          )
        },
        _react2.default.createElement(
          _reactBootstrap.Label,
          { id: 'teitoku-timer', bsStyle: style },
          _react2.default.createElement(_reactFontawesome2.default, { name: 'calendar' })
        )
      )
    );
  }
}

const CountdownContent = ({ moments }) => _react2.default.createElement(
  'div',
  null,
  ['Practice', 'Quest', 'Senka', 'EO'].map(name => _react2.default.createElement(
    'div',
    { className: 'info-tooltip-entry', key: name },
    _react2.default.createElement(
      'span',
      { className: 'info-tooltip-item' },
      __(`Next ${name}`)
    ),
    _react2.default.createElement(
      'span',
      null,
      _react2.default.createElement(_countdownTimer.CountdownNotifierLabel, {
        timerKey: `next-${name}`,
        completeTime: +moments[name],
        resolveTime: resolveDayTime,
        getLabelStyle: getLabelStyle
      })
    )
  ))
);

const admiralInfoSelector = (0, _reselect.createSelector)([_selectors.basicSelector], basic => ({
  level: (0, _lodash.get)(basic, 'api_level', -1),
  nickname: (0, _lodash.get)(basic, 'api_nickname', ''),
  rank: (0, _lodash.get)(basic, 'api_rank', 0),
  maxShip: (0, _lodash.get)(basic, 'api_max_chara', 0),
  maxSlotitem: (0, _lodash.get)(basic, 'api_max_slotitem', 0)
}));

const numCheckSelector = (0, _reselect.createSelector)([_selectors.configSelector], config => ({
  shipNumCheck: (0, _lodash.get)(config, 'poi.mapStartCheck.ship.enable', false),
  minShipNum: (0, _lodash.get)(config, 'poi.mapStartCheck.ship.minFreeSlots', 4),
  slotNumCheck: (0, _lodash.get)(config, 'poi.mapStartCheck.item.enable', false),
  minSlotNum: (0, _lodash.get)(config, 'poi.mapStartCheck.item.minFreeSlots', 10)
}));

exports.default = (0, _reactRedux.connect)(state => _extends({}, admiralInfoSelector(state), {
  equipNum: Object.keys(state.info.equips).length,
  shipNum: Object.keys(state.info.ships).length,
  dropCount: state.sortie.dropCount
}, numCheckSelector(state)))(function TeitokuPanel({ level, nickname, rank, maxShip, maxSlotitem,
  equipNum, shipNum, dropCount,
  shipNumCheck, minShipNum, slotNumCheck, minSlotNum }) {
  const shipNumClass = shipNumCheck && maxShip - (shipNum + dropCount) < minShipNum ? 'alert alert-warning' : '';
  const slotNumClass = slotNumCheck && maxSlotitem - equipNum < minSlotNum ? 'alert alert-warning' : '';
  return _react2.default.createElement(
    _reactBootstrap.Panel,
    { bsStyle: 'default', className: 'teitoku-panel' },
    level >= 0 ? _react2.default.createElement(
      'div',
      null,
      _react2.default.createElement(
        _reactBootstrap.OverlayTrigger,
        { placement: 'bottom', overlay: _react2.default.createElement(
            _reactBootstrap.Tooltip,
            { id: 'teitoku-exp', className: 'info-tooltip' },
            _react2.default.createElement(ExpContent, null)
          ) },
        _react2.default.createElement(
          'span',
          null,
          `Lv. ${level}　`,
          _react2.default.createElement(
            'span',
            { className: 'nickname' },
            nickname
          ),
          _react2.default.createElement(
            'span',
            { id: 'user-rank' },
            `　[${rankName[rank]}]　`
          )
        )
      ),
      _react2.default.createElement(
        'span',
        null,
        __('Ships: ')
      ),
      _react2.default.createElement(
        'span',
        { className: shipNumClass },
        shipNum + dropCount,
        ' / ',
        maxShip
      ),
      _react2.default.createElement(
        'span',
        { style: { marginLeft: '1em' } },
        __('Equip.: ')
      ),
      _react2.default.createElement(
        'span',
        { className: slotNumClass },
        equipNum,
        ' / ',
        maxSlotitem
      ),
      _react2.default.createElement(CountDownControl, null)
    ) : _react2.default.createElement(
      'div',
      null,
      `${__('Admiral [Not logged in]')}　${__("Ships: ")}：? / ?　${__("Equip.: ")}：? / ?`
    )
  );
});
module.exports = exports['default'];