"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

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

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

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

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

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

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

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

var _helpers = require("../../common/api/helpers");

var _get = _interopRequireDefault(require("lodash/get"));

var _constants = require("@instructure/quiz-common/lib/constants");

var _formatMessage = _interopRequireDefault(require("@instructure/quiz-i18n/lib/format-message"));

var getBankEntries = function getBankEntries(bankId, useBankSearch) {
  var params = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
  var page = params.page,
      text = params.text,
      filters = params.filters;
  var basePath = "/api/banks/".concat(bankId, "/bank_entries");
  var searchPath = "".concat(basePath, "/search");
  var interaction_type_ids = (0, _get.default)(filters, 'interactionTypes', []);
  var tag_ids = (0, _get.default)(filters, 'tags', []);
  var urlParams = {
    page: page,
    text: text,
    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 _PaginatedFetcher.default({
      callType: _constants.GET_BANK_ENTRIES_CALL,
      onError: (0, _helpers.handleError)(dispatch, "Abrufen von Pool-Eintr\xE4gen fehlgeschlagen."),
      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, _slicedToArray2.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 (text === void 0 && noInteractions && noTags) {
          filterUpdate = [(0, _banks.setBankFilters)(bankId, r[0].filters)];
        }
      }

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

exports.getBankEntries = getBankEntries;

var getBankEntry = function getBankEntry(bankId, bankEntryId) {
  var url = "/api/banks/".concat(bankId, "/bank_entries/").concat(bankEntryId);
  return function (dispatch, getState) {
    var fetcher = new _Fetcher.default({
      callType: _constants.GET_BANK_ENTRY_CALL,
      onError: (0, _helpers.handleError)(dispatch, "Abrufen von Pool-Eintrag fehlgeschlagen.")
    });
    return fetcher.get(url).then(function (response) {
      dispatch((0, _callHandlers.handleBankEntryResponse)(response));
      return response;
    });
  };
};

exports.getBankEntry = getBankEntry;

var cloneBankEntry = function cloneBankEntry(bankEntry, createEntryCb) {
  var updateBankEntryCb = arguments.length > 2 && arguments[2] !== void 0 ? 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
      }));
    });
  };
};

exports.cloneBankEntry = cloneBankEntry;

var createEntryAndBankEntry = function createEntryAndBankEntry(bankId, entry, bankEntry, createEntryCb) {
  var createBankEntryCb = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : createBankEntry;
  return function (dispatch, getState) {
    return dispatch(createEntryCb(entry, bankId, 'bank')).then(function (entryData) {
      return dispatch(createBankEntryCb(bankId, bankEntry.entryType, entryData.id));
    });
  };
};

exports.createEntryAndBankEntry = createEntryAndBankEntry;

var createBankEntry = function createBankEntry(bankId, entryType, entryId) {
  var url = "/api/banks/".concat(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 _Fetcher.default({
      callType: _constants.CREATE_BANK_ENTRY_CALL,
      onError: (0, _helpers.handleError)(dispatch, "Erstellen von Pool-Eintrag fehlgeschlagen.")
    });
    return fetcher.post(url, {
      body: newBankEntryData
    }).then(function (response) {
      dispatch([(0, _callHandlers.handleBankEntryResponse)(response), (0, _banks.associateEntries)(bankId, [response.id]), (0, _ui.clear)("".concat(_constants.BANKS_BANK_ENTRY_PAGINATION, ":").concat(bankId)), (0, _banks2.getBank)(bankId)]);
      return response;
    });
  };
};

exports.createBankEntry = createBankEntry;

var updateBankEntry = function updateBankEntry(bankId, bankEntryId, params) {
  var url = "/api/banks/".concat(bankId, "/bank_entries/").concat(bankEntryId);
  return function (dispatch, getState) {
    var fetcher = new _Fetcher.default({
      callType: _constants.UPDATE_BANK_ENTRY_CALL,
      onError: (0, _helpers.handleError)(dispatch, "Aktualisieren von Pool-Eintrag fehlgeschlagen.")
    });
    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)("".concat(_constants.BANKS_BANK_ENTRY_PAGINATION, ":").concat(bankId)), (0, _ui.clear)("".concat(_constants.BANKS_BANK_ENTRY_PAGINATION, ":").concat(params.bankId)), (0, _banks2.getBank)(bankId), (0, _banks2.getBank)(params.bankId)]);
      }

      return response;
    });
  };
};

exports.updateBankEntry = updateBankEntry;

var removeBankEntry = function removeBankEntry(bankId, bankEntryId) {
  var url = "/api/banks/".concat(bankId, "/bank_entries/").concat(bankEntryId);
  return function (dispatch, getState) {
    var fetcher = new _Fetcher.default({
      callType: _constants.REMOVE_BANK_ENTRY_CALL,
      onError: (0, _helpers.handleError)(dispatch, "Entfernen von Pool-Eintrag fehlgeschlagen.")
    });
    return fetcher.delete(url).then(function (response) {
      return dispatch([(0, _banks.disassociateEntry)(bankId, bankEntryId), (0, _ui.clear)("".concat(_constants.BANKS_BANK_ENTRY_PAGINATION, ":").concat(bankId)), (0, _banks2.getBank)(bankId), (0, _bankEntries.archiveBankEntry)(bankEntryId)]);
    });
  };
};

exports.removeBankEntry = removeBankEntry;