'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.removeBankEntry = exports.updateBankEntry = exports.createBankEntry = exports.createEntryAndBankEntry = exports.cloneBankEntry = exports.getBankEntry = exports.getBankEntries = exports.tagAssociations = undefined;

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray');

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

var _ui = require('../../common/actions/ui');

var _Fetcher = require('../../common/util/Fetcher');

var _Fetcher2 = _interopRequireDefault(_Fetcher);

var _PaginatedFetcher = require('../../common/util/PaginatedFetcher');

var _PaginatedFetcher2 = _interopRequireDefault(_PaginatedFetcher);

var _banks = require('../../common/actions/banks');

var _callHandlers = require('../../common/api/callHandlers');

var _bankEntries = require('../../common/actions/bankEntries');

var _banks2 = require('./banks');

var _tagAssociations = require('./tagAssociations');

var tagAssociations = _interopRequireWildcard(_tagAssociations);

var _helpers = require('./helpers');

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _isUndefined = require('lodash/isUndefined');

var _isUndefined2 = _interopRequireDefault(_isUndefined);

var _constants = require('../../constants');

var _formatMessage = require('../../common/format-message');

var _formatMessage2 = _interopRequireDefault(_formatMessage);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

exports.tagAssociations = tagAssociations;
var getBankEntries = exports.getBankEntries = function getBankEntries(bankId, useBankSearch) {
  var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var page = params.page,
      search = params.search,
      filters = params.filters;

  var basePath = '/api/banks/' + bankId + '/bank_entries';
  var searchPath = basePath + '/search';

  var interaction_type_ids = (0, _get2.default)(filters, 'interactionTypes', []);
  var tag_ids = (0, _get2.default)(filters, 'tags', []);
  var urlParams = {
    page: page,
    text: search,
    interaction_type_ids: interaction_type_ids,
    tag_ids: tag_ids
  };

  return function (dispatch, getState) {
    var getSearchIds = function getSearchIds(json) {
      return json.entries.map(function (e) {
        return e.id;
      });
    };
    var getRecordIds = useBankSearch ? getSearchIds : null;
    var fetcher = new _PaginatedFetcher2.default({
      callType: _constants.GET_BANK_ENTRIES_CALL,
      onError: (0, _helpers.handleBankError)(dispatch, 'Failed to fetch bank entries.'),
      getRecordIds: getRecordIds
    });

    var path = useBankSearch ? searchPath : basePath;
    return fetcher.get(path, urlParams).then(function (r) {
      var _ref = useBankSearch ? [r[0].entries, r[1]] : r,
          _ref2 = (0, _slicedToArray3.default)(_ref, 2),
          response = _ref2[0],
          pageData = _ref2[1];

      var filterUpdate = [];
      if (useBankSearch) {
        var noInteractions = interaction_type_ids.length === 0;
        var noTags = tag_ids.length === 0;
        if ((0, _isUndefined2.default)(search) && noInteractions && noTags) {
          filterUpdate = [(0, _banks.setBankFilters)(bankId, r[0].filters)];
        }
      }

      dispatch([].concat((0, _toConsumableArray3.default)(filterUpdate), [(0, _callHandlers.handleBankEntriesResponse)(response), (0, _banks.associateEntries)(bankId, response.map(function (be) {
        return be.id;
      }))]));

      return pageData;
    });
  };
};

var getBankEntry = exports.getBankEntry = function getBankEntry(bankId, bankEntryId) {
  var url = '/api/banks/' + bankId + '/bank_entries/' + bankEntryId;
  return function (dispatch, getState) {
    var fetcher = new _Fetcher2.default({
      callType: _constants.GET_BANK_ENTRY_CALL,
      onError: (0, _helpers.handleBankError)(dispatch, 'Failed to fetch bank entry.')
    });
    return fetcher.get(url).then(function (response) {
      if (response.entry_type === 'Item') {
        dispatch(tagAssociations.getItemTagAssociations(response.entry.id));
      } else if (response.entry_type == 'Stimulus') {
        dispatch(tagAssociations.getStimulusTagAssociations(response.entry.id));
      }
      dispatch((0, _callHandlers.handleBankEntryResponse)(response));
      return response;
    });
  };
};

var cloneBankEntry = exports.cloneBankEntry = function cloneBankEntry(bankEntry, createEntryCb) {
  var updateBankEntryCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : updateBankEntry;

  var entry = bankEntry.getEntry();
  var workingEntry = entry.getWorkingInstance();
  var bankId = bankEntry.bankId;
  return function (dispatch, getState) {
    return dispatch(createEntryCb(workingEntry, bankId, 'bank', entry.id)).then(function (entryData) {
      return dispatch(updateBankEntryCb(bankId, bankEntry.id, { entryId: entryData.id }));
    });
  };
};

var createEntryAndBankEntry = exports.createEntryAndBankEntry = function createEntryAndBankEntry(bankId, entry, bankEntry, createEntryCb) {
  var createBankEntryCb = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : createBankEntry;

  return function (dispatch, getState) {
    return dispatch(createEntryCb(entry, bankId, 'bank')).then(function (entryData) {
      return dispatch(createBankEntryCb(bankId, bankEntry.entryType, entryData.id));
    });
  };
};

var createBankEntry = exports.createBankEntry = function createBankEntry(bankId, entryType, entryId) {
  var url = '/api/banks/' + bankId + '/bank_entries';
  return function (dispatch, getState) {
    var newBankEntryData = JSON.stringify({
      bank_entry: {
        bank_id: bankId,
        entry_type: entryType,
        entry_id: entryId
      }
    });

    var fetcher = new _Fetcher2.default({
      callType: _constants.CREATE_BANK_ENTRY_CALL,
      onError: (0, _helpers.handleBankError)(dispatch, 'Failed to create bank entry.')
    });
    return fetcher.post(url, { body: newBankEntryData }).then(function (response) {
      dispatch([(0, _callHandlers.handleBankEntryResponse)(response), (0, _banks.associateEntries)(bankId, [response.id]), (0, _ui.clear)(_constants.BANKS_BANK_ENTRY_PAGINATION + ':' + bankId), (0, _banks2.getBank)(bankId)]);
      return response;
    });
  };
};

var updateBankEntry = exports.updateBankEntry = function updateBankEntry(bankId, bankEntryId, params) {
  var url = '/api/banks/' + bankId + '/bank_entries/' + bankEntryId;
  return function (dispatch, getState) {
    var fetcher = new _Fetcher2.default({
      callType: _constants.UPDATE_BANK_ENTRY_CALL,
      onError: (0, _helpers.handleBankError)(dispatch, 'Failed to update bank entry.')
    });
    var reqParams = { bank_id: params.bankId, entry_id: params.entryId };
    var updateBankEntryParams = {
      body: JSON.stringify({ bank_entry: reqParams })
    };
    return fetcher.patch(url, updateBankEntryParams).then(function (response) {
      dispatch([(0, _callHandlers.handleBankEntryResponse)(response), (0, _banks.associateEntries)(response.bank_id, [response.id])]);
      if (params.bankId && bankId !== params.bankId) {
        dispatch([(0, _ui.clear)(_constants.BANKS_BANK_ENTRY_PAGINATION + ':' + bankId), (0, _ui.clear)(_constants.BANKS_BANK_ENTRY_PAGINATION + ':' + params.bankId), (0, _banks2.getBank)(bankId), (0, _banks2.getBank)(params.bankId)]);
      }
      return response;
    });
  };
};

var removeBankEntry = exports.removeBankEntry = function removeBankEntry(bankId, bankEntryId) {
  var url = '/api/banks/' + bankId + '/bank_entries/' + bankEntryId;
  return function (dispatch, getState) {
    var fetcher = new _Fetcher2.default({
      callType: _constants.REMOVE_BANK_ENTRY_CALL,
      onError: (0, _helpers.handleBankError)(dispatch, 'Failed to remove bank entry.')
    });
    return fetcher.delete(url).then(function (response) {
      return dispatch([(0, _banks.disassociateEntry)(bankId, bankEntryId), (0, _ui.clear)(_constants.BANKS_BANK_ENTRY_PAGINATION + ':' + bankId), (0, _banks2.getBank)(bankId), (0, _bankEntries.archiveBankEntry)(bankEntryId)]);
    });
  };
};