'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getQuizEntry = getQuizEntry;
exports.getQuizEntries = getQuizEntries;
exports.createStimulusAndQuizEntry = createStimulusAndQuizEntry;
exports.createItemAndQuizEntry = createItemAndQuizEntry;
exports.createQuizEntry = createQuizEntry;
exports.updateQuizEntry = updateQuizEntry;
exports.cloneQuizEntry = cloneQuizEntry;
exports.moveQuizEntry = moveQuizEntry;
exports.removeQuizEntry = removeQuizEntry;
exports.removeStimulusQuizEntry = removeStimulusQuizEntry;

var _pick = require('lodash/pick');

var _pick2 = _interopRequireDefault(_pick);

var _pickBy = require('lodash/pickBy');

var _pickBy2 = _interopRequireDefault(_pickBy);

var _humps = require('humps');

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

var _Fetcher2 = _interopRequireDefault(_Fetcher);

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

var _ExhaustivePaginatedFetcher2 = _interopRequireDefault(_ExhaustivePaginatedFetcher);

var _scrolling = require('../../common/actions/scrolling');

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

var _noop = require('../../common/util/noop');

var _noop2 = _interopRequireDefault(_noop);

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

var _items = require('./items');

var _stimuli = require('./stimuli');

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

var _quizzes = require('../../common/actions/quizzes');

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

var _quizzes2 = require('../../common/api/quizzes');

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

// =====================
// =====================
//       GET INDEX
// =====================
// =====================

var handleQuizEntriesGet = function handleQuizEntriesGet(dispatch, quizId, quizEntries) {
  dispatch([(0, _callHandlers.handleQuizEntriesResponse)(quizEntries, quizId), (0, _quizzes.associateQuizEntries)(quizId, quizEntries)]);
  return quizEntries;
};

function getQuizEntry(quizId, quizEntryId) {
  var url = '/api/quizzes/' + quizId + '/quiz_entries/' + quizEntryId;
  return function (dispatch, getState) {
    var fetcher = new _Fetcher2.default();
    return fetcher.get(url).then(function (data) {
      return handleQuizEntriesGet(dispatch, quizId, [data]);
    });
  };
}

function getQuizEntries(quizId) {
  var cb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop2.default;

  var url = '/api/quizzes/' + quizId + '/quiz_entries';
  return function (dispatch, getState) {
    var fetcher = new _ExhaustivePaginatedFetcher2.default();
    return fetcher.get(url).then(function (data) {
      return handleQuizEntriesGet(dispatch, quizId, data);
    }).then(cb);
  };
}

// =====================
// =====================
//       CREATE
// =====================
// =====================

function createEntryAndQuizEntry(quizId, entry, quizEntry, entryCreationCb, quizEntryCreationCb) {
  return function (dispatch, getState) {
    var entryProperties = quizEntry.getProperties();
    return dispatch(entryCreationCb(entry, quizId, 'quiz')).then(function (entryData) {
      return dispatch(quizEntryCreationCb(quizId, entryData.id, quizEntry.get('entryType'), entryProperties));
    });
  };
}

function createStimulusAndQuizEntry(quizId, stimulus, quizEntry) {
  var stimulusCreationCb = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _stimuli.createStimulus;
  var quizEntryCreationCb = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : createQuizEntry;

  return createEntryAndQuizEntry(quizId, stimulus, quizEntry, stimulusCreationCb, quizEntryCreationCb);
}

function createItemAndQuizEntry(quizId, item, quizEntry) {
  var itemCreationCb = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _items.createItem;
  var quizEntryCreationCb = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : createQuizEntry;

  return createEntryAndQuizEntry(quizId, item, quizEntry, itemCreationCb, quizEntryCreationCb);
}

function createQuizEntry(quizId, entryId, entryType, entryProperties) {
  var requireFocus = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;

  var url = '/api/quizzes/' + quizId + '/quiz_entries';
  var quizEntryParams = Object.assign({
    quizId: quizId,
    entryType: entryType,
    entryId: entryId
  }, entryProperties);
  var body = JSON.stringify({ quiz_entry: quizEntryParams });
  return function (dispatch, getState) {
    var fetcher = new _Fetcher2.default({
      callType: _constants.CREATE_QUIZ_ENTRY_CALL,
      onError: (0, _helpers.handleBankError)(dispatch)
    });
    return fetcher.post(url, { body: body }).then(function (response) {
      var scrollCallback = function scrollCallback() {
        return dispatch((0, _scrolling.scrollToItem)(response.id, requireFocus));
      };
      dispatch(getQuizEntries(quizId, scrollCallback));
    });
  };
}

// =====================
// =====================
//    UPDATE, CLONE & MOVE
// =====================
// =====================

// UPDATE HELPER
function updateBody(updatedProperties) {
  var properties = updatedProperties.properties;
  if (properties && properties.selection === 'all') {
    properties.sampleNum = null;
  }
  var validProperties = Object.keys(updatedProperties).map(_humps.decamelize).concat(['properties']);
  var entryProperties = (0, _pick2.default)({
    points_possible: parseFloat(updatedProperties.pointsPossible),
    position: updatedProperties.position,
    stimulus_quiz_entry_id: updatedProperties.stimulusQuizEntryId,
    entry_id: updatedProperties.entryId,
    entry_type: updatedProperties.entryType,
    properties: properties
  }, validProperties);

  var isDefined = function isDefined(val) {
    return val !== null && val !== void 0;
  };
  var entryPropsToUpdate = (0, _pickBy2.default)(entryProperties, isDefined);

  return JSON.stringify({ quiz_entry: entryPropsToUpdate });
}

function updateQuizEntry(quizId, quizEntryId, updatedProperties) {
  var url = '/api/quizzes/' + quizId + '/quiz_entries/' + quizEntryId;
  var fetcher = new _Fetcher2.default({
    callType: _constants.UPDATE_QUIZ_ENTRY_CALL
  });

  var body = updateBody(updatedProperties);
  return function (dispatch, getState) {
    return fetcher.patch(url, { body: body }).then(function (qeData) {
      dispatch((0, _callHandlers.handleQuizEntryResponse)(qeData));
      if (Object.keys(updatedProperties).includes('position')) {
        dispatch((0, _ui.set)(_constants.MOVED_QUIZ_ENTRY, quizEntryId));
      }
    });
  };
}

function cloneQuizEntry(quizId, quizEntryId, updatedProperties) {
  var url = '/api/quizzes/' + quizId + '/quiz_entries/' + quizEntryId + '/clone';
  var fetcher = new _Fetcher2.default({
    callType: _constants.CLONE_QUIZ_ENTRY_CALL
  });

  var body = updateBody(updatedProperties);
  return function (dispatch, getState) {
    return fetcher.post(url, { body: body }).then(function (qeData) {
      dispatch((0, _callHandlers.handleQuizEntryResponse)(qeData));
      return qeData;
    }).then(function () {
      return dispatch((0, _quizzes2.getExistingQuizAndItems)(quizId));
    });
  };
}

function moveQuizEntry(quizId, position, stimulusQuizEntryId, quizEntryId, moveTempItem) {
  var updateAction = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : updateQuizEntry;

  return function (dispatch, getState) {
    return dispatch(updateAction(quizId, quizEntryId, { position: position, stimulusQuizEntryId: stimulusQuizEntryId })).then(function () {
      return dispatch(getQuizEntries(quizId));
    }).then(moveTempItem);
  };
}

// =====================
// =====================
//       DESTROY
// =====================
// =====================

function quizEntryDeleted(dispatch, quizEntry) {
  setTimeout(function () {
    dispatch((0, _ui.set)(_constants.DELETED_QUIZ_ENTRY, {
      position: quizEntry.position,
      inStimulus: quizEntry.isInStimulus
    }));
  }, 100);
}

function removeQuizEntry(quizId, quizEntry) {
  var getQuizEntriesThunk = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : getQuizEntries;

  var url = '/api/quizzes/' + quizId + '/quiz_entries/' + quizEntry.id;

  return function (dispatch, getState) {
    var fetcher = new _Fetcher2.default({
      callType: _constants.DELETE_QUIZ_ENTRY_CALL
    });

    var handleQuizEntryDelete = function handleQuizEntryDelete() {
      dispatch([(0, _quizzes.disassociateQuizEntry)(quizId, quizEntry.id), getQuizEntries(quizId)]);
      quizEntryDeleted(dispatch, quizEntry);
    };

    return fetcher.delete(url).then(handleQuizEntryDelete);
  };
}

function removeStimulusQuizEntry(quizId, stimulusEntry, childEntries) {
  var getQuizEntriesThunk = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : getQuizEntries;

  var url = '/api/quizzes/' + quizId + '/quiz_entries/' + stimulusEntry.id + '/stimuli';

  return function (dispatch, getState) {
    var fetcher = new _Fetcher2.default({
      callType: _constants.DELETE_QUIZ_ENTRY_CALL
    });

    var body = JSON.stringify({ child_ids: childEntries.map(function (entry) {
        return entry.id;
      }) });

    var handleQuizEntryDelete = function handleQuizEntryDelete() {
      dispatch([(0, _quizzes.disassociateQuizEntry)(quizId, stimulusEntry.id), getQuizEntries(quizId)]);
      quizEntryDeleted(dispatch, stimulusEntry);
    };

    return fetcher.delete(url, { body: body }).then(handleQuizEntryDelete);
  };
}