'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = undefined;

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = require('babel-runtime/helpers/get');

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _dec,
    _desc,
    _value,
    _class,
    _default_ht_number = Intl.NumberFormat('ht', { style: 'decimal' }).format;

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _interactionPoints = require('quiz-interactions/lib/util/interactionPoints');

var _interactionPoints2 = _interopRequireDefault(_interactionPoints);

var _instUIMessages = require('../../common/util/instUIMessages');

var _reduxRecord = require('./reduxRecord');

var _reduxRecord2 = _interopRequireDefault(_reduxRecord);

var _Item2 = require('./Item');

var _Item3 = _interopRequireDefault(_Item2);

var _Bank2 = require('./Bank');

var _Bank3 = _interopRequireDefault(_Bank2);

var _Stimulus2 = require('./Stimulus');

var _Stimulus3 = _interopRequireDefault(_Stimulus2);

var _BankEntry2 = require('./BankEntry');

var _BankEntry3 = _interopRequireDefault(_BankEntry2);

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

var _immutableHelpers = require('../util/immutableHelpers');

var _withStateCache = require('../util/withStateCache');

var _withStateCache2 = _interopRequireDefault(_withStateCache);

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

var _formatMessage2 = _interopRequireDefault(_formatMessage);

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

function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
  var desc = {};
  Object['ke' + 'ys'](descriptor).forEach(function (key) {
    desc[key] = descriptor[key];
  });
  desc.enumerable = !!desc.enumerable;
  desc.configurable = !!desc.configurable;

  if ('value' in desc || desc.initializer) {
    desc.writable = true;
  }

  desc = decorators.slice().reverse().reduce(function (desc, decorator) {
    return decorator(target, property, desc) || desc;
  }, desc);

  if (context && desc.initializer !== void 0) {
    desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
    desc.initializer = undefined;
  }

  if (desc.initializer === void 0) {
    Object['define' + 'Property'](target, property, desc);
    desc = null;
  }

  return desc;
}

var acceptedVerbs = [_constants.REMOVE, _constants.MOVE, _constants.EDIT];

var QuizEntry = (_dec = (0, _withStateCache2.default)(function () {
  return [['quizEntries'], ['modifications', 'quizEntries']];
}), (_class = function (_ReduxRecord) {
  (0, _inherits3.default)(QuizEntry, _ReduxRecord);

  function QuizEntry() {
    var _ref;

    var _temp, _this, _ret;

    (0, _classCallCheck3.default)(this, QuizEntry);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = QuizEntry.__proto__ || Object.getPrototypeOf(QuizEntry)).call.apply(_ref, [this].concat(args))), _this), _this.__getStimulusEntries = function () {
      var childEntries = _this.getState().get('quizEntries', (0, _immutable.Map)()).filter(function (entry) {
        return entry.get('stimulusQuizEntryId') === _this.id;
      });

      var temporaryItem = _this.getState().getIn(['modifications', 'quizEntries', _constants.TEMPORARY_QUIZ_ENTRY_ID]);

      if (temporaryItem && temporaryItem.get('stimulusQuizEntryId') === _this.id) {
        childEntries = childEntries.set(temporaryItem.id, QuizEntry.create(temporaryItem));
      }

      var quizEntries = childEntries.map(function (entry) {
        return QuizEntry.create(entry);
      }).sortBy(function (qe) {
        return qe.position;
      }).toList();

      return quizEntries || (0, _immutable.List)();
    }, _this.__getBankEntryEntries = function () {
      if (_this.hasStimulus) {
        return _this.__getStimulusEntries();
      } else {
        return (0, _immutable.List)([_this]);
      }
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.default)(QuizEntry, [{
    key: 'getErrors',
    value: function getErrors() {
      return (0, _get3.default)(QuizEntry.prototype.__proto__ || Object.getPrototypeOf(QuizEntry.prototype), 'getErrors', this).call(this, this).merge({
        sampleNum: this.sampleNumErrors(),
        deletedBank: this.deletedBankErrors(),
        pointsPossible: this.pointsPossibleErrors()
      });
    }
  }, {
    key: 'isNumber',
    value: function isNumber(numString) {
      return Number(numString).toString() === numString;
    }
  }, {
    key: 'sampleNumErrors',
    value: function sampleNumErrors() {
      var errors = [];
      var selection = this.selection;
      if (!this.isBank || selection === 'all' || this.isArchivedBank) {
        return (0, _instUIMessages.toErrors)(errors);
      }
      var sample = this.properties.get('sampleNum', '');
      var parsedNumber = parseInt(sample, 10);
      if (parsedNumber < 1) {
        errors.push('Dwe sipery\xE8 o egal a 1');
      }
      if (parsedNumber > this.getEntry().itemEntryCount) {
        var _s, _n, _i, _v;

        errors.push((_s = this.getEntry().itemEntryCount, _n = +_s, (_i = Math.floor(Math.abs(+_s)), _v = (_s + '.').split('.')[1].length, _i === 1 && _v === 0 ? 'Kantite maksim\xF2m depase (bank sa agen 1 kesyon)' : 'Kantite maksim\xF2m depase (bank sa a gen ' + _default_ht_number(this.getEntry().itemEntryCount) + ' kesyon)')));
      }
      if (!Number.isInteger(Number(sample)) || isNaN(parsedNumber) || !this.isNumber(sample)) {
        errors.push('Dwe yon nonm antye');
      }
      return (0, _instUIMessages.toErrors)(errors);
    }
  }, {
    key: 'deletedBankErrors',
    value: function deletedBankErrors() {
      var errors = [];
      if (this.isArchivedBank) {
        errors.push('bank eleman sa a pa egziste ank\xF2. Tanpri seleksyone yon bank valid.');
      }
      return (0, _instUIMessages.toErrors)(errors);
    }
  }, {
    key: 'pointsPossibleErrors',
    value: function pointsPossibleErrors() {
      var errors = [];
      var possible = this.pointsPossible;
      if (!this.isNumber(possible.toString())) {
        errors.push('Dwe yon nonm');
      }
      return (0, _instUIMessages.toErrors)(errors);
    }
  }, {
    key: 'getEntry',
    value: function getEntry() {
      var _this2 = this;

      var entry = void 0;
      if (this.entry === _constants.TEMPORARY_ITEM_ID) {
        entry = _Item3.default.create(this.getState().getIn(['modifications', 'items', _constants.TEMPORARY_ITEM_ID]));
      } else if (this.entry === _constants.TEMPORARY_STIMULUS_ID) {
        entry = _Stimulus3.default.create(this.getState().getIn(['modifications', 'stimuli', _constants.TEMPORARY_STIMULUS_ID]));
      }

      if (entry === void 0) {
        var entryId = this.entryId || this.entry.get('id');
        var entryCreator = {
          Bank: function Bank() {
            return _Bank3.default.create(_this2.getState().getIn(['banks', entryId]));
          },
          BankEntry: function BankEntry() {
            return _BankEntry3.default.create(_this2.getState().getIn(['bankEntries', entryId]));
          },
          Item: function Item() {
            return _Item3.default.create(_this2.getState().getIn(['items', entryId]));
          },
          Stimulus: function Stimulus() {
            return _Stimulus3.default.create(_this2.getState().getIn(['stimuli', entryId]));
          }
        };

        if (!entryCreator[this.entryType]) return;
        entry = entryCreator[this.entryType]();
      }

      entry.quizEntry = this;
      return entry;
    }
  }, {
    key: 'getItem',
    value: function getItem() {
      var entry = this.getEntry();

      var itemCreator = {
        BankEntry: function BankEntry() {
          return entry.getEntry();
        },
        Item: function Item() {
          return entry;
        }
      }[this.entryType];
      if (!itemCreator) return;

      // Assume we want working item if accessed on working quiz entry.
      var item = itemCreator();
      if (!item) return;

      var currentItem = this.isWorkingInstance ? item.getWorkingInstance() : item;
      return currentItem.mergeWith(_immutableHelpers.mergeDeepOnlyMaps, this.properties.get('itemOverrides'));
    }
  }, {
    key: 'getNestedEntries',


    // This will currently trigger rerendering of all stimuli if any QuizEntry changes.
    // Possibly the `withStateCache` decorator could be made more sophisticated to deal
    // with this flaw.
    value: function getNestedEntries() {
      var _this3 = this;

      var getNestedEntriesFunction = {
        Bank: function Bank() {
          return (0, _immutable.List)([_this3]);
        },
        BankEntry: this.__getBankEntryEntries,
        Item: function Item() {
          return (0, _immutable.List)([_this3]);
        },
        Stimulus: this.__getStimulusEntries
      }[this.entryType];

      return getNestedEntriesFunction ? getNestedEntriesFunction() : (0, _immutable.List)();
    }
  }, {
    key: 'getProperties',
    value: function getProperties() {
      return {
        points_possible: this.pointsPossible && parseFloat(this.pointsPossible),
        position: this.position && Math.ceil(this.position),
        stimulus_quiz_entry_id: this.stimulusQuizEntryId
      };
    }
  }, {
    key: 'isImmutable',
    value: function isImmutable() {
      return this.status === 'immutable';
    }
  }, {
    key: 'hasModifications',
    value: function hasModifications() {
      return !_immutable2.default.is(this.getWorkingInstance().delete('isWorkingInstance'), this.delete('isWorkingInstance'));
    }
  }, {
    key: 'getWorkingInstance',
    value: function getWorkingInstance() {
      var data = this.mergeWith(_immutableHelpers.mergeDeepOnlyMaps, this.getState().getIn(['modifications', 'quizEntries', this.id])).set('isWorkingInstance', true);
      return QuizEntry.create(data);
    }
  }, {
    key: 'generateScreenReaderText',


    /* eslint-disable format-message/no-missing-params */
    value: function generateScreenReaderText(displayPosition, verb) {
      if (!acceptedVerbs.includes(verb)) {
        // eslint-disable-next-line no-console
        console.error(verb + ' not an accepted verb. Must be one of ' + acceptedVerbs);
      }

      // Due to possible translation nuances, the remove, edit, and move verbs are broken out into
      // their own possible string so that translators can better translate the meaning
      var type = void 0;
      if (this.isStimulus || this.isBank) {
        type = this.isStimulus ? 'Stimulus' : 'Bank';
        if (this.positionSlots > 1) {
          var opts = { type: type, start: displayPosition, end: displayPosition + this.positionSlots };
          return {
            Remove: 'Elimine ' + opts.type + ' ki gen eleman ' + _default_ht_number(opts.start) + ' nan ' + _default_ht_number(opts.end) + '.',
            Edit: 'Modifye ' + opts.type + ' ki gen eleman ' + _default_ht_number(opts.start) + ' nan ' + _default_ht_number(opts.end) + '.',
            Move: 'Deplase ' + opts.type + ' ki gen eleman ' + _default_ht_number(opts.start) + ' nan ' + _default_ht_number(opts.end) + '.'
          }[verb];
        } else if (this.positionSlots === 1) {
          var _opts = { type: type, start: displayPosition };
          return {
            Remove: 'Elimine ' + _opts.type + ' ki gen eleman ki genyen ' + _default_ht_number(_opts.start) + '.',
            Edit: 'Modifye ' + _opts.type + ' ki gen eleman ' + _default_ht_number(_opts.start) + '.',
            Move: 'Deplase ' + _opts.type + ' ki gen eleman ' + _default_ht_number(_opts.start) + '.'
          }[verb];
        } else {
          var _opts2 = { type: type, start: displayPosition, end: displayPosition + this.positionSlots };
          return {
            Remove: 'Elimine vid ' + _opts2.type + ' ant pozisyon ' + _default_ht_number(_opts2.start) + ' e ' + _default_ht_number(_opts2.end) + '.',
            Edit: 'Modifye vid ' + _opts2.type + ' ant pozisyon ' + _default_ht_number(_opts2.start) + ' e ' + _default_ht_number(_opts2.end) + '.',
            Move: 'Deplase vid ' + _opts2.type + ' ant pozisyon ' + _default_ht_number(_opts2.start) + ' e ' + _default_ht_number(_opts2.end) + '.'
          }[verb];
        }
      } else {
        type = this.isBankEntry ? 'Sezi Bank' : 'Eleman';
        var _opts3 = { verb: verb, type: type, position: displayPosition };
        return {
          Remove: 'Elimine ' + _opts3.type + ' nan pozisyon ' + _default_ht_number(_opts3.position),
          Edit: 'Modifye ' + _opts3.type + ' nan pozisyon ' + _default_ht_number(_opts3.position) + '.',
          Move: 'Deplase ' + _opts3.type + ' nan pozisyon ' + _default_ht_number(_opts3.position) + '.'
        }[verb];
      }
    }
    /* eslint-enable format-message/no-missing-params */

  }, {
    key: 'positionToDisplay',
    value: function positionToDisplay(displayPosition) {
      if (this.isBank && this.sizeOfBank > 1 && this.sampleNum !== 1) {
        return _default_ht_number(displayPosition) + ' - ' + _default_ht_number(displayPosition + (this.sizeOfBank - 1));
      }
      return _default_ht_number(displayPosition);
    }
  }, {
    key: 'state',
    value: function state() {
      return this.getState();
    }
  }, {
    key: 'isArchivedBankEntry',
    get: function get() {
      return this.isBankEntry && this.getEntry().archived;
    }
  }, {
    key: 'isArchivedBank',
    get: function get() {
      return this.isBank && this.getEntry().archived;
    }
  }, {
    key: 'hasStimulus',
    get: function get() {
      return this.isStimulus || this.isBankEntry && this.getEntry().getEntry().isStimulus;
    }
  }, {
    key: 'hasNestedRecords',
    get: function get() {
      return this.hasStimulus;
    }
  }, {
    key: 'isBank',
    get: function get() {
      return this.entryType === 'Bank';
    }
  }, {
    key: 'isBankEntry',
    get: function get() {
      return this.entryType === 'BankEntry';
    }
  }, {
    key: 'isStimulus',
    get: function get() {
      return this.entryType === 'Stimulus';
    }
  }, {
    key: 'isItem',
    get: function get() {
      return this.entryType === 'Item';
    }
  }, {
    key: 'isInStimulus',
    get: function get() {
      return !isNaN(parseInt(this.stimulusQuizEntryId, 10));
    }
  }, {
    key: 'isTemporary',
    get: function get() {
      return this.id === _constants.TEMPORARY_QUIZ_ENTRY_ID;
    }
  }, {
    key: 'type',
    get: function get() {
      return this.entryType;
    }
  }, {
    key: 'pointsPossible',
    get: function get() {
      var item = this.getItem();
      var itemPoints = item && (0, _interactionPoints2.default)(item.toJS());
      return itemPoints === void 0 ? this.get('pointsPossible') : itemPoints;
    }
  }, {
    key: 'sampleNum',
    get: function get() {
      return parseInt(this.properties.get('sampleNum'), 10);
    }
  }, {
    key: 'selection',
    get: function get() {
      return this.properties.get('selection') || (this.sampleNum > 0 ? 'rand' : 'all');
    }
  }, {
    key: 'sizeOfBank',
    get: function get() {
      if (!this.isBank) return 0;
      return this.sampleNum > 0 ? this.sampleNum : this.getEntry().itemEntryCount;
    }
  }, {
    key: 'positionSlots',
    get: function get() {
      if (this.hasNestedRecords) {
        return this.getNestedEntries().size;
      }
      return 1;
    }
  }, {
    key: 'displayPositionSlots',
    get: function get() {
      if (this.isBank) {
        return this.sampleNum || this.getEntry().itemEntryCount;
      }
      if (this.hasStimulus) {
        return this.getNestedEntries().reduce(function (sum, quizEntry) {
          return sum + quizEntry.displayPositionSlots;
        }, 0);
      }
      return 1;
    }
  }]);
  return QuizEntry;
}((0, _reduxRecord2.default)({
  id: '0',
  entryEditable: true,
  entry: (0, _immutable.Map)(),
  entryId: null,
  entryType: null,
  isWorkingInstance: false,
  pointsPossible: 1,
  position: null,
  properties: (0, _immutable.Map)(),
  regradeAdjustedPointsPossible: null,
  regradeAdjustedScoringData: null,
  status: 'mutable',
  stimulusQuizEntryId: null
})), (_applyDecoratedDescriptor(_class.prototype, 'getNestedEntries', [_dec], Object.getOwnPropertyDescriptor(_class.prototype, 'getNestedEntries'), _class.prototype)), _class));
exports.default = QuizEntry;