"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getExistingBankAndEntries = getExistingBankAndEntries;
exports.updateSharedBankPermission = exports.getSharedBanks = exports.shareBank = exports.deleteBank = exports.updateBank = exports.createBank = exports.getBank = exports.getAllBanks = exports.getBanks = void 0;

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

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

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

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

var _ExhaustivePaginatedFetcher = _interopRequireDefault(require("../../common/util/ExhaustivePaginatedFetcher"));

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

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

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

var _sharedBanks = require("../../common/actions/sharedBanks");

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

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

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

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

var banksApiEndpoint = '/api/banks';
var DEFAULT_PAGE_SIZE = 100;

var getBanks = function getBanks() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function (dispatch, getState) {
    var fetcher = new _PaginatedFetcher.default();
    return fetcher.get(banksApiEndpoint, params).then(function (_ref) {
      var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
          response = _ref2[0],
          pageData = _ref2[1];

      dispatch((0, _callHandlers.handleBanksResponse)(response));
      return pageData;
    });
  };
};

exports.getBanks = getBanks;

var getAllBanks = function getAllBanks() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  return function (dispatch, getState) {
    var fetcher = new _ExhaustivePaginatedFetcher.default();
    return fetcher.get(banksApiEndpoint, (0, _objectSpread2.default)({
      per_page: DEFAULT_PAGE_SIZE
    }, params)).then(function (response) {
      dispatch((0, _callHandlers.handleBanksResponse)(response));
      return response.map(function (x) {
        return x.id;
      });
    });
  };
};

exports.getAllBanks = getAllBanks;

var getBank = function getBank(bankId) {
  return function (dispatch, getState) {
    var fetcher = new _Fetcher.default({
      onError: (0, _helpers.handleError)(dispatch, "Impossibile recuperare banca.")
    });
    return fetcher.get("".concat(banksApiEndpoint, "/").concat(bankId)).then(function (response) {
      return dispatch((0, _callHandlers.handleBanksResponse)([response]));
    });
  };
};

exports.getBank = getBank;

var createBank = function createBank(newBank) {
  return function (dispatch, getState) {
    var newBankData = JSON.stringify({
      bank: {
        title: newBank.title,
        language: newBank.language
      }
    });
    var fetcher = new _Fetcher.default();
    return fetcher.post(banksApiEndpoint, {
      body: newBankData
    }).then(function (bankData) {
      dispatch([(0, _callHandlers.handleBankResponse)(bankData), (0, _ui.clear)(_constants.BANKS_BANK_PAGINATION)]);
      return bankData;
    });
  };
};

exports.createBank = createBank;

function getExistingBankAndEntries(bankId) {
  return function (dispatch, getState) {
    return dispatch([(0, _ui.clear)("".concat(_constants.BANKS_BANK_ENTRY_PAGINATION, ":").concat(bankId)), getBank(bankId)]);
  };
}

var updateBank = function updateBank(bank) {
  var url = "".concat(banksApiEndpoint, "/").concat(bank.id);
  return function (dispatch, getState) {
    var updatedBankData = JSON.stringify({
      bank: {
        title: bank.title
      }
    });
    var fetcher = new _Fetcher.default({
      callType: _constants.UPDATE_BANK_CALL,
      onError: (0, _helpers.handleError)(dispatch, "Impossibile aggiornare banca.")
    });
    return fetcher.patch(url, {
      body: updatedBankData
    }).then(function (bankData) {
      dispatch([(0, _callHandlers.handleBankResponse)(bankData), (0, _ui.clear)(_constants.BANKS_BANK_PAGINATION)]);
      return bankData;
    });
  };
};

exports.updateBank = updateBank;

var deleteBank = function deleteBank(bankId) {
  var url = "".concat(banksApiEndpoint, "/").concat(bankId);
  return function (dispatch, getState) {
    var fetcher = new _Fetcher.default({
      callType: _constants.DELETE_BANK_CALL,
      onError: (0, _helpers.handleError)(dispatch, "Impossibile eliminare banca.")
    });
    return fetcher.delete(url).then(function () {
      dispatch((0, _ui.clear)(_constants.BANKS_BANK_PAGINATION));

      if (getState().getIn(['ui', 'activeBankId']) === bankId) {
        dispatch([(0, _ui.newActiveBankEntry)(void 0), (0, _ui.newActiveBank)(void 0)]);
      }

      var activeQuizId = getState().getIn(['quizzes', 'activeQuizId'], false);

      if (activeQuizId) {
        dispatch((0, _banks.archiveBank)(bankId));
        getState().get('bankEntries', []).forEach(function (bankEntry) {
          if (bankEntry.get('bankId') === bankId) {
            dispatch((0, _bankEntries.archiveBankEntry)(bankEntry.get('id')));
          }
        });
      }
    });
  };
};

exports.deleteBank = deleteBank;

var shareBank = function shareBank(_shareBank, getUserInfo) {
  var url = "".concat(banksApiEndpoint, "/").concat(_shareBank.bankId, "/shared_banks");
  return function (dispatch, getState) {
    var shareBankData = JSON.stringify({
      shared_bank: {
        user_uuid: _shareBank.userUuid,
        bank_id: _shareBank.bankId,
        permission: _shareBank.permission
      }
    });
    var fetcher = new _Fetcher.default({
      onError: (0, _helpers.handleError)(dispatch, "Impossibile condividere banca.")
    });
    return fetcher.post(url, {
      body: shareBankData
    }).then(function (sharedBankInfo) {
      getUserInfo(sharedBankInfo.user_uuid).then(function (userInfo) {
        var sharedBank = {
          id: sharedBankInfo.id,
          userUuid: userInfo[0].uuid,
          fullName: userInfo[0].fullName,
          avatar: userInfo[0].avatar,
          permission: sharedBankInfo.permission,
          bankId: _shareBank.bankId
        };
        dispatch((0, _callHandlers.handleShareBankResponse)(sharedBank));
      });
    });
  };
};

exports.shareBank = shareBank;

var getSharedBanks = function getSharedBanks(bank, getUserInfo) {
  var url = "".concat(banksApiEndpoint, "/").concat(bank.id, "/shared_banks");
  var sharedBanks = [];
  return function (dispatch, getState) {
    var fetcher = new _Fetcher.default({
      onError: (0, _helpers.handleError)(dispatch, "Impossibile recuperare banche condivise.")
    });
    return fetcher.get(url).then(function (sharedBanksInfo) {
      // if the API returns no data, we manually add the bank's owner
      if (sharedBanksInfo.length === 0) {
        sharedBanksInfo.push({
          id: '-1',
          bank_id: bank.id,
          user_uuid: bank.owner,
          permission: _constants.CAN_EDIT
        });
      }

      var uuids = sharedBanksInfo.map(function (sharedBank) {
        return sharedBank.user_uuid;
      });
      getUserInfo(uuids).then(function (usersInfo) {
        usersInfo.forEach(function (userInfo) {
          var shareBankInfo = sharedBanksInfo.find(function (sharedBank) {
            return sharedBank.user_uuid === userInfo.uuid;
          });

          if (shareBankInfo) {
            var sharedBank = {
              id: shareBankInfo.id,
              userUuid: userInfo.uuid,
              fullName: userInfo.fullName,
              avatar: userInfo.avatar,
              permission: shareBankInfo.permission,
              bankId: shareBankInfo.bank_id
            };
            sharedBanks.push(sharedBank);
          }
        });
        dispatch((0, _callHandlers.handleShareBanksResponse)(sharedBanks));
      });
    });
  };
};

exports.getSharedBanks = getSharedBanks;

var updateSharedBankPermission = function updateSharedBankPermission(bankId, sharedBankId, permission) {
  var url = "".concat(banksApiEndpoint, "/").concat(bankId, "/shared_banks/").concat(sharedBankId);
  return function (dispatch, getState) {
    var shareBankData = JSON.stringify({
      shared_bank: {
        permission: permission
      }
    });
    var fetcher = new _Fetcher.default({
      onError: (0, _helpers.handleError)(dispatch, "Impossibile aggiornare permesso banca condiviso.")
    });
    return fetcher.patch(url, {
      body: shareBankData
    }).then(function (sharedBank) {
      if (permission === _constants.REMOVED_ACCESS) {
        dispatch((0, _ui.clear)(_constants.BANKS_BANK_PAGINATION));
        dispatch((0, _sharedBanks.removeSharedBank)(sharedBankId));
      } else {// code that dispatches updateShareBank action
      }
    });
  };
};

exports.updateSharedBankPermission = updateSharedBankPermission;