'use strict';

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

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

var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);

exports.getExistingBankAndEntries = getExistingBankAndEntries;

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

var _Fetcher2 = _interopRequireDefault(_Fetcher);

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

var _PaginatedFetcher2 = _interopRequireDefault(_PaginatedFetcher);

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

var _ExhaustivePaginatedFetcher2 = _interopRequireDefault(_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 = require('../../common/format-message');

var _formatMessage2 = _interopRequireDefault(_formatMessage);

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

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

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

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

var getBanks = exports.getBanks = function getBanks() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  return function (dispatch, getState) {
    var fetcher = new _PaginatedFetcher2.default();
    return fetcher.get(banksApiEndpoint, params).then(function (_ref) {
      var _ref2 = (0, _slicedToArray3.default)(_ref, 2),
          response = _ref2[0],
          pageData = _ref2[1];

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

var getAllBanks = exports.getAllBanks = function getAllBanks() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  return function (dispatch, getState) {
    var fetcher = new _ExhaustivePaginatedFetcher2.default();
    return fetcher.get(banksApiEndpoint, Object.assign({ per_page: DEFAULT_PAGE_SIZE }, params)).then(function (response) {
      dispatch((0, _callHandlers.handleBanksResponse)(response));
      return response.map(function (x) {
        return x.id;
      });
    });
  };
};

var getBank = exports.getBank = function getBank(bankId) {
  return function (dispatch, getState) {
    var fetcher = new _Fetcher2.default({
      onError: (0, _helpers.handleBankError)(dispatch, 'Failed to fetch bank.')
    });
    return fetcher.get(banksApiEndpoint + '/' + bankId).then(function (response) {
      return dispatch((0, _callHandlers.handleBanksResponse)([response]));
    });
  };
};

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

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

var updateBank = exports.updateBank = function updateBank(bank) {
  var url = banksApiEndpoint + '/' + bank.id;
  return function (dispatch, getState) {
    var updatedBankData = JSON.stringify({
      bank: {
        title: bank.title
      }
    });
    var fetcher = new _Fetcher2.default({
      callType: _constants.UPDATE_BANK_CALL,
      onError: (0, _helpers.handleBankError)(dispatch, 'Failed to update bank.')
    });
    return fetcher.patch(url, { body: updatedBankData }).then(function (bankData) {
      dispatch([(0, _callHandlers.handleBankResponse)(bankData), (0, _ui.clear)(_constants.BANKS_BANK_PAGINATION)]);
      return bankData;
    });
  };
};

var deleteBank = exports.deleteBank = function deleteBank(bankId) {
  var url = banksApiEndpoint + '/' + bankId;
  return function (dispatch, getState) {
    var fetcher = new _Fetcher2.default({
      callType: _constants.DELETE_BANK_CALL,
      onError: (0, _helpers.handleBankError)(dispatch, 'Failed to delete bank.')
    });
    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')));
          }
        });
      }
    });
  };
};

var shareBank = exports.shareBank = function shareBank(_shareBank, getUserInfo) {
  var url = banksApiEndpoint + '/' + _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 _Fetcher2.default({
      onError: (0, _helpers.handleBankError)(dispatch, 'Failed to share bank.')
    });
    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));
      });
    });
  };
};

var getSharedBanks = exports.getSharedBanks = function getSharedBanks(bank, getUserInfo) {
  var url = banksApiEndpoint + '/' + bank.id + '/shared_banks';
  var sharedBanks = [];
  return function (dispatch, getState) {
    var fetcher = new _Fetcher2.default({
      onError: (0, _helpers.handleBankError)(dispatch, 'Failed to fetch shared banks.')
    });
    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));
      });
    });
  };
};

var updateSharedBankPermission = exports.updateSharedBankPermission = function updateSharedBankPermission(bankId, sharedBankId, permission) {
  var url = banksApiEndpoint + '/' + bankId + '/shared_banks/' + sharedBankId;
  return function (dispatch, getState) {
    var shareBankData = JSON.stringify({
      shared_bank: {
        permission: permission
      }
    });

    var fetcher = new _Fetcher2.default({
      onError: (0, _helpers.handleBankError)(dispatch, 'Failed to update shared bank permission.')
    });
    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
      }
    });
  };
};