'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 _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _dec, _dec2, _dec3, _desc, _value, _class, _class2, _temp;

var _immutable = require('immutable');

var _instructureValidations = require('instructure-validations');

var _validationHelpers = require('quiz-interactions/lib/util/validationHelpers');

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

var _formatMessage2 = _interopRequireDefault(_formatMessage);

var _QuizAnalysis = require('./QuizAnalysis');

var _QuizAnalysis2 = _interopRequireDefault(_QuizAnalysis);

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

var _reduxRecord2 = _interopRequireDefault(_reduxRecord);

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

var _withStateCache2 = _interopRequireDefault(_withStateCache);

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 Quiz = (_dec = (0, _withStateCache2.default)(function (quiz) {
  return [['quizEntries'], ['modifications', 'quizEntries']];
}), _dec2 = (0, _withStateCache2.default)(function (quiz) {
  return [['quizEntries'], ['modifications', 'quizEntries'], ['modifications', 'quizzes', quiz.id, 'quizEntries']];
}), _dec3 = (0, _withStateCache2.default)(function (quiz) {
  return [['modifications', 'quizzes']];
}), (_class = (_temp = _class2 = function (_ReduxRecord) {
  (0, _inherits3.default)(Quiz, _ReduxRecord);

  function Quiz() {
    (0, _classCallCheck3.default)(this, Quiz);
    return (0, _possibleConstructorReturn3.default)(this, (Quiz.__proto__ || Object.getPrototypeOf(Quiz)).apply(this, arguments));
  }

  (0, _createClass3.default)(Quiz, [{
    key: 'getTimeLimit',
    value: function getTimeLimit() {
      return this.hasTimeLimit ? this.sessionTimeLimitInSeconds : 0;
    }
  }, {
    key: 'getQuizSessions',
    value: function getQuizSessions() {
      var _this2 = this;

      return this.getState().get('quizSessions').filter(function (data) {
        return data.get('quiz') === _this2.id;
      }).map(function (qsd) {
        return _this2.stateHelper().findQuizSession(qsd.get('id'));
      }).valueSeq().toList();
    }
  }, {
    key: 'getQuizSessionsForUser',
    value: function getQuizSessionsForUser(userId) {
      return this.getQuizSessions().filter(function (quizSession) {
        return quizSession.getIn(['user', 'id']) === userId;
      });
    }
  }, {
    key: 'getQuizEntries',
    value: function getQuizEntries() {
      return this.getRelationList('quizEntries', 'findQuizEntry').sortBy(function (qe) {
        return qe.position;
      });
    }
  }, {
    key: 'getItemAnalyses',
    value: function getItemAnalyses() {
      // TODO: Sort this based on the ordering on the quiz build page
      return this.getRelationList('itemAnalyses', 'findItemAnalysis');
    }
  }, {
    key: 'getQuizAnalysis',
    value: function getQuizAnalysis() {
      return new _QuizAnalysis2.default(this.getState().getIn(['reporting', 'quiz_analysis', this.quizAnalysis]));
    }

    // If you call this.getWorkingInstance().getQuizEntries() manually, then
    // changes to the other parts of a quiz (e.g., changing the title) will
    // invalidate the cache, since the result of getWorkingInstance() will
    // be a new object. This method explicitly caches by only the fields that are
    // relevant to the working quiz entries.

  }, {
    key: 'getWorkingQuizEntries',
    value: function getWorkingQuizEntries() {
      return this.getWorkingInstance().getQuizEntries();
    }
  }, {
    key: 'getWorkingInstance',
    value: function getWorkingInstance() {
      var _this3 = this;

      var modData = this.getState().getIn(['modifications', 'quizzes', this.id]) || (0, _immutable.Map)();
      var data = this.merge(modData.update('quizEntries', (0, _immutable.List)(), // default
      function (qi) {
        // without custom merge, quizEntries List will be
        // overwritten completely, and wouldnt' support
        // temporary quizEntry associations well
        return qi.concat(_this3.quizEntries.toJS());
      }));

      return Quiz.create(data, this.getState());
    }
  }, {
    key: 'getLatestImport',
    value: function getLatestImport() {
      var _this4 = this;

      var allImports = this.getState().get('qtiImports');
      var importsForQuiz = allImports.valueSeq().filter(function (qtiImport) {
        return qtiImport.get('parentId') === _this4.id && qtiImport.get('parentType') === 'Quiz';
      });
      var latestImport = importsForQuiz.maxBy(function (i) {
        return i.get('id');
      });
      var id = latestImport && latestImport.get('id');
      return this.stateHelper().findImport(id);
    }
  }, {
    key: 'isLoaded',
    value: function isLoaded() {
      return this.id !== '0';
    }
  }, {
    key: 'isImporting',
    value: function isImporting() {
      return this.status === 'importing';
    }
  }, {
    key: 'canImport',
    value: function canImport() {
      // associating the quizEntry will change the quiz status in the
      // db but it wont return this info, we we'll check the quizEntry
      // count in addition to the status
      return this.status === 'uninitialized' && this.quizEntries.size === 0;
    }
  }, {
    key: 'isOneQuestionAtATime',
    value: function isOneQuestionAtATime() {
      return this.oneAtATimeType === 'question';
    }
  }, {
    key: 'state',
    value: function state() {
      return this.getState();
    }
  }]);
  return Quiz;
}((0, _reduxRecord2.default)({
  allowBacktracking: true,
  calculatorType: 'none',
  contextId: null,
  dueAt: null,
  hasTimeLimit: false,
  id: '0',
  instructions: 'Adicionar instru\xE7\xF5es ...',
  itemAnalyses: (0, _immutable.List)(),
  items: (0, _immutable.List)(),
  lockAt: null,
  oneAtATimeType: null,
  outcomeAlignmentSetGuid: null,
  owner: null,
  quizAnalysis: '0',
  quizEntries: (0, _immutable.List)(),
  quizEntriesCount: 0,
  requireStudentAccessCode: false,
  sessionTimeLimitInSeconds: null,
  shuffleAnswers: false,
  shuffleQuestions: false,
  status: null,
  studentAccessCode: null,
  title: 'Adicionar t\xEDtulo ...',
  filterIpAddress: false,
  filters: (0, _immutable.Map)(),
  valid: true
})), _class2.validations = {
  title: [(0, _instructureValidations.rule)('presence', { message: (0, _validationHelpers.presenceMessage)('T\xEDtulo de question\xE1rio') })]
}, _temp), (_applyDecoratedDescriptor(_class.prototype, 'getQuizEntries', [_dec], Object.getOwnPropertyDescriptor(_class.prototype, 'getQuizEntries'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'getWorkingQuizEntries', [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, 'getWorkingQuizEntries'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'getWorkingInstance', [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, 'getWorkingInstance'), _class.prototype)), _class));
exports.default = Quiz;