'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; };

exports.reducer = reducer;

var _tools = require('views/utils/tools');

// Returns a clone
// Don't worry about -1 because it won't cause error
function removeEquips(equips, idList) {
  equips = Object.assign({}, equips);
  idList.forEach(itemId => delete equips[itemId]);
  return equips;
}

function reducer(state = {}, { type, postBody, body }) {
  const { getStore } = window;
  switch (type) {
    case '@@Response/kcsapi/api_get_member/slot_item':
      {
        const bodyEquips = (0, _tools.indexify)(body);
        return (0, _tools.pickExisting)((0, _tools.compareUpdate)(state, bodyEquips), bodyEquips);
      }
    case '@@Response/kcsapi/api_get_member/require_info':
      {
        const bodyEquips = (0, _tools.indexify)(body.api_slot_item);
        return (0, _tools.pickExisting)((0, _tools.compareUpdate)(state, bodyEquips), bodyEquips);
      }
    case '@@Response/kcsapi/api_req_kousyou/createitem':
      if (body.api_create_flag == 1) {
        const { api_slot_item } = body;
        return _extends({}, state, {
          [api_slot_item.api_id]: api_slot_item
        });
      }
      break;
    case '@@Response/kcsapi/api_req_kousyou/getship':
      if (body.api_slotitem) {
        return _extends({}, state, (0, _tools.indexify)(body.api_slotitem));
      }
      break;
    case '@@Response/kcsapi/api_req_kousyou/destroyitem2':
      return removeEquips(state, postBody.api_slotitem_ids.split(','));
    case '@@Response/kcsapi/api_req_kaisou/lock':
      {
        const { api_slotitem_id } = postBody;
        const { api_locked } = body;
        return _extends({}, state, {
          [api_slotitem_id]: _extends({}, state[api_slotitem_id], {
            api_locked: api_locked
          })
        });
      }
    case '@@Response/kcsapi/api_req_kaisou/powerup':
      return removeEquips(state, [].concat.apply([], postBody.api_id_items.split(',').map(shipId => getStore(`info.ships.${shipId}.api_slot`) || [])));
    case '@@Response/kcsapi/api_req_kousyou/destroyship':
      return removeEquips(state, getStore(`info.ships.${postBody.api_ship_id}.api_slot`));
    case '@@Response/kcsapi/api_req_kousyou/remodel_slot':
      {
        const { api_use_slot_id, api_remodel_flag, api_after_slot } = body;
        if (api_use_slot_id != null) {
          state = removeEquips(state, api_use_slot_id);
        }
        if (api_remodel_flag == 1 && api_after_slot != null) {
          state = _extends({}, state, {
            [api_after_slot.api_id]: api_after_slot
          });
        }
        return state;
      }
  }
  return state;
}