'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.isModified = exports.isSavePending = exports.isReadPending = exports.getValidationErrors = exports.getNewSubrecordCsid = exports.getNewData = exports.getRelationUpdatedTimestamp = exports.getSubrecordCsid = exports.getError = exports.getData = undefined;

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _recordDataHelpers = require('../helpers/recordDataHelpers');

var _configHelpers = require('../helpers/configHelpers');

var _login = require('../actions/login');

var _logout = require('../actions/logout');

var _record = require('../actions/record');

var _relation = require('../actions/relation');

var _idGenerator = require('../actions/idGenerator');

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var BASE_NEW_RECORD_KEY = '';

var unsavedRecordKey = function unsavedRecordKey(subrecordName) {
  return subrecordName ? BASE_NEW_RECORD_KEY + '/' + subrecordName : BASE_NEW_RECORD_KEY;
};

var getCurrentData = function getCurrentData(state, csid) {
  return state.getIn([csid, 'data', 'current']);
};
var setCurrentData = function setCurrentData(state, csid, data) {
  return state.setIn([csid, 'data', 'current'], data);
};

var getBaselineData = function getBaselineData(state, csid) {
  return state.getIn([csid, 'data', 'baseline']);
};
var setBaselineData = function setBaselineData(state, csid, data) {
  return state.setIn([csid, 'data', 'baseline'], data);
};

var addFieldInstance = function addFieldInstance(state, action) {
  var _action$meta = action.meta,
      csid = _action$meta.csid,
      path = _action$meta.path,
      recordTypeConfig = _action$meta.recordTypeConfig;


  var data = getCurrentData(state, csid);

  if (!data) {
    return state;
  }

  var value = (0, _recordDataHelpers.deepGet)(data, path);
  var list = _immutable2.default.List.isList(value) ? value : _immutable2.default.List.of(value);

  var fieldDescriptor = (0, _get2.default)(recordTypeConfig, ['fields'].concat(_toConsumableArray((0, _configHelpers.dataPathToFieldDescriptorPath)(path))));
  var defaultData = (0, _recordDataHelpers.applyDefaults)(fieldDescriptor);

  var updatedData = (0, _recordDataHelpers.deepSet)(data, path, list.push(defaultData));

  return setCurrentData(state, csid, updatedData);
};

var doCreateNew = function doCreateNew(state, config, recordTypeConfig, cloneCsid, subrecordName) {
  var data = void 0;

  if (cloneCsid) {
    data = (0, _recordDataHelpers.cloneRecordData)(recordTypeConfig, getCurrentData(state, cloneCsid));
  }

  if (!data) {
    data = (0, _recordDataHelpers.createRecordData)(recordTypeConfig);
  }

  var csid = unsavedRecordKey(subrecordName);

  var updatedState = state.delete(csid);

  var subrecords = recordTypeConfig.subrecords;


  if (subrecords) {
    Object.keys(subrecords).forEach(function (name) {
      var subrecordConfig = subrecords[name];
      var csidField = subrecordConfig.csidField;


      var cloneSubrecordCsid = void 0;

      if (csidField) {
        cloneSubrecordCsid = (0, _recordDataHelpers.deepGet)(data, csidField);
      }

      if (!cloneSubrecordCsid) {
        var subrecordType = subrecordConfig.recordType;
        var subrecordTypeConfig = (0, _get2.default)(config, ['recordTypes', subrecordType]);
        var subrecordCsid = state.getIn([cloneCsid, 'subrecord', name]);

        updatedState = doCreateNew(updatedState, config, subrecordTypeConfig, subrecordCsid, name);

        cloneSubrecordCsid = csid + '/' + name;

        if (csidField) {
          data = (0, _recordDataHelpers.deepSet)(data, csidField, cloneSubrecordCsid);
        }
      }

      updatedState = updatedState.setIn([csid, 'subrecord', name], cloneSubrecordCsid);
    });
  }

  updatedState = setBaselineData(updatedState, csid, data);
  updatedState = setCurrentData(updatedState, csid, data);

  return updatedState;
};

var createNewRecord = function createNewRecord(state, action) {
  var _action$meta2 = action.meta,
      config = _action$meta2.config,
      recordTypeConfig = _action$meta2.recordTypeConfig,
      cloneCsid = _action$meta2.cloneCsid;


  return doCreateNew(state, config, recordTypeConfig, cloneCsid);
};

var deleteFieldValue = function deleteFieldValue(state, action) {
  var _action$meta3 = action.meta,
      csid = _action$meta3.csid,
      path = _action$meta3.path;


  var data = getCurrentData(state, csid);

  if (!data) {
    return state;
  }

  var updatedData = (0, _recordDataHelpers.deepDelete)(data, path);

  return setCurrentData(state, csid, updatedData);
};

var moveFieldValue = function moveFieldValue(state, action) {
  var _action$meta4 = action.meta,
      csid = _action$meta4.csid,
      path = _action$meta4.path,
      newPosition = _action$meta4.newPosition;


  var data = getCurrentData(state, csid);

  if (!data) {
    return state;
  }

  var listPath = path.slice(0, -1);
  var oldPosition = path[path.length - 1];

  var list = (0, _recordDataHelpers.deepGet)(data, listPath);

  if (!_immutable2.default.List.isList(list)) {
    return state;
  }

  var value = list.get(oldPosition);

  list = list.delete(oldPosition);
  list = list.insert(newPosition, value);

  var updatedData = (0, _recordDataHelpers.deepSet)(data, listPath, list);

  return setCurrentData(state, csid, updatedData);
};

var setFieldValue = function setFieldValue(state, action) {
  var _action$meta5 = action.meta,
      csid = _action$meta5.csid,
      path = _action$meta5.path;


  var data = getCurrentData(state, csid);

  if (!data) {
    return state;
  }

  var newValue = action.payload;
  var updatedData = (0, _recordDataHelpers.deepSet)(data, path, newValue);
  var updatedState = setCurrentData(state, csid, updatedData);

  return updatedState;
};

var handleFieldComputeFulfilled = function handleFieldComputeFulfilled(state, action) {
  var _action$meta6 = action.meta,
      csid = _action$meta6.csid,
      path = _action$meta6.path;


  var data = getCurrentData(state, csid);

  if (!data) {
    return state;
  }

  if (path.length === 0) {
    // The entire record was computed.

    var computedData = action.payload;
    var updatedData = data.mergeDeep(computedData);
    var updatedState = setCurrentData(state, csid, updatedData);

    return updatedState;
  }

  // TODO: Handle an individual field being computed.

  return state;
};

var handleRecordReadFulfilled = function handleRecordReadFulfilled(state, action) {
  var _action$meta7 = action.meta,
      csid = _action$meta7.csid,
      recordTypeConfig = _action$meta7.recordTypeConfig;


  var data = (0, _recordDataHelpers.normalizeRecordData)(recordTypeConfig, _immutable2.default.fromJS(action.payload.data));

  var updatedState = state.deleteIn([csid, 'isReadPending']);

  updatedState = setBaselineData(updatedState, csid, data);
  updatedState = setCurrentData(updatedState, csid, data);

  return updatedState;
};

var handleRecordSaveFulfilled = function handleRecordSaveFulfilled(state, action) {
  var _action$meta8 = action.meta,
      csid = _action$meta8.csid,
      recordTypeConfig = _action$meta8.recordTypeConfig,
      relatedSubjectCsid = _action$meta8.relatedSubjectCsid;


  var data = (0, _recordDataHelpers.normalizeRecordData)(recordTypeConfig, _immutable2.default.fromJS(action.payload.data));

  var updatedState = state;

  updatedState = updatedState.deleteIn([csid, 'isSavePending']);

  updatedState = setBaselineData(updatedState, csid, data);
  updatedState = setCurrentData(updatedState, csid, data);

  if (relatedSubjectCsid) {
    updatedState = updatedState.setIn([relatedSubjectCsid, 'relationUpdatedTime'], (0, _recordDataHelpers.getUpdatedTimestamp)(data));
  }

  return updatedState;
};

var revertRecord = function revertRecord(state, action) {
  var _action$meta9 = action.meta,
      recordTypeConfig = _action$meta9.recordTypeConfig,
      csid = _action$meta9.csid;


  var baselineData = getBaselineData(state, csid);

  var updatedState = setCurrentData(state, csid, baselineData);

  // Revert subrecords.

  var subrecords = updatedState.getIn([csid, 'subrecord']);

  if (subrecords) {
    subrecords.forEach(function (subrecordCsid) {
      updatedState = revertRecord(updatedState, {
        meta: {
          csid: subrecordCsid
        }
      });
    });
  }

  // Revert any cached subrecord csids that originated from fields in the record.

  var configuredSubrecords = (0, _get2.default)(recordTypeConfig, 'subrecords');

  if (configuredSubrecords) {
    Object.entries(configuredSubrecords).forEach(function (entry) {
      var _entry = _slicedToArray(entry, 2),
          subrecordName = _entry[0],
          subrecordConfig = _entry[1];

      var csidField = subrecordConfig.csidField;


      if (csidField) {
        var revertedSubrecordCsid = (0, _recordDataHelpers.deepGet)(baselineData, csidField);

        updatedState = updatedState.setIn([csid, 'subrecord', subrecordName], revertedSubrecordCsid);

        // Revert the reattached subrecord.

        updatedState = revertRecord(updatedState, {
          meta: {
            csid: revertedSubrecordCsid
          }
        });
      }
    });
  }

  return updatedState;
};

var handleSubrecordCreated = function handleSubrecordCreated(state, action) {
  var _action$meta10 = action.meta,
      csid = _action$meta10.csid,
      csidField = _action$meta10.csidField,
      subrecordName = _action$meta10.subrecordName,
      subrecordCsid = _action$meta10.subrecordCsid,
      isDefault = _action$meta10.isDefault;


  var updatedState = state.setIn([csid, 'subrecord', subrecordName], subrecordCsid);

  if (csidField) {
    var currentData = getCurrentData(state, csid);
    var baselineData = getBaselineData(state, csid);

    if (isDefault && currentData === baselineData) {
      // This subrecord was created as the default for the container. Set the csid field in both
      // the baseline and current data, so it won't be considered a modification.

      var updatedData = (0, _recordDataHelpers.deepSet)(baselineData, csidField, subrecordCsid);

      updatedState = setBaselineData(updatedState, csid, updatedData);
      updatedState = setCurrentData(updatedState, csid, updatedData);
    } else {
      var _updatedData = (0, _recordDataHelpers.deepSet)(currentData, csidField, subrecordCsid);

      updatedState = setCurrentData(updatedState, csid, _updatedData);
    }
  }

  return updatedState;
};

var createNewSubrecord = function createNewSubrecord(state, action) {
  var _action$meta11 = action.meta,
      config = _action$meta11.config,
      csid = _action$meta11.csid,
      csidField = _action$meta11.csidField,
      subrecordName = _action$meta11.subrecordName,
      subrecordTypeConfig = _action$meta11.subrecordTypeConfig,
      cloneCsid = _action$meta11.cloneCsid,
      isDefault = _action$meta11.isDefault;


  var updatedState = doCreateNew(state, config, subrecordTypeConfig, cloneCsid, subrecordName);

  var subrecordCsid = unsavedRecordKey(subrecordName);

  updatedState = handleSubrecordCreated(updatedState, {
    meta: {
      csid: csid,
      csidField: csidField,
      subrecordName: subrecordName,
      subrecordCsid: subrecordCsid,
      isDefault: isDefault
    }
  });

  return updatedState;
};

var handleSubjectRelationsUpdated = function handleSubjectRelationsUpdated(state, action) {
  // Currently relations are only ever created (not updated), and we don't bother to retrieve
  // the relation record after creation. Technically we should retrieve the new relation
  // record and use its updatedAt value here, but that's an extra request. For now just use the
  // current local time, at least until there's some additional reason to retrieve the full
  // relation record.

  var subjectCsid = action.meta.csid;
  // TODO: Move this into action creator. (This makes the reducer not pure).
  var newUpdatedTime = new Date().toISOString();

  if (state.has(subjectCsid)) {
    return state.setIn([subjectCsid, 'relationUpdatedTime'], newUpdatedTime);
  }

  return state;
};

var handleCreateIDFulfilled = function handleCreateIDFulfilled(state, action) {
  var _action$meta12 = action.meta,
      csid = _action$meta12.csid,
      path = _action$meta12.path;


  var data = getCurrentData(state, csid);

  if (!data) {
    return state;
  }

  var newValue = action.payload.data;
  var updatedData = (0, _recordDataHelpers.deepSet)(data, path, newValue);
  var updatedState = setCurrentData(state, csid, updatedData);

  return updatedState;
};

var handleValidationFailed = function handleValidationFailed(state, action) {
  var errors = action.payload;

  var _action$meta13 = action.meta,
      csid = _action$meta13.csid,
      path = _action$meta13.path;


  return state.setIn([csid, 'validation'].concat(_toConsumableArray(path)), errors);
};

var handleValidationPassed = function handleValidationPassed(state, action) {
  var _action$meta14 = action.meta,
      csid = _action$meta14.csid,
      path = _action$meta14.path;


  return state.deleteIn([csid, 'validation'].concat(_toConsumableArray(path)));
};

var handleTransitionFulfilled = function handleTransitionFulfilled(state, action) {
  var _action$meta15 = action.meta,
      csid = _action$meta15.csid,
      transitionName = _action$meta15.transitionName,
      recordTypeConfig = _action$meta15.recordTypeConfig,
      relatedSubjectCsid = _action$meta15.relatedSubjectCsid,
      updatedTimestamp = _action$meta15.updatedTimestamp;


  var updatedState = state.deleteIn([csid, 'isSavePending']);

  if (transitionName === 'delete') {
    updatedState = updatedState.delete(csid);
  } else {
    var newData = (0, _get2.default)(action, ['payload', 'data']);

    if (newData) {
      var data = (0, _recordDataHelpers.normalizeRecordData)(recordTypeConfig, _immutable2.default.fromJS(newData));

      updatedState = setBaselineData(updatedState, csid, data);
      updatedState = setCurrentData(updatedState, csid, data);
    }
  }

  if (relatedSubjectCsid) {
    updatedState = updatedState.setIn([relatedSubjectCsid, 'relationUpdatedTime'], updatedTimestamp);
  }

  return updatedState;
};

var detachSubrecord = function detachSubrecord(state, action) {
  return createNewSubrecord(state, action);
};

var clearAll = function clearAll(state) {
  return state.clear();
};

exports.default = function () {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _immutable2.default.Map();
  var action = arguments[1];

  switch (action.type) {
    case _record.VALIDATION_FAILED:
      return handleValidationFailed(state, action);
    case _record.VALIDATION_PASSED:
      return handleValidationPassed(state, action);
    case _record.ADD_FIELD_INSTANCE:
      return addFieldInstance(state, action);
    case _record.CREATE_NEW_RECORD:
      return createNewRecord(state, action);
    case _record.CREATE_NEW_SUBRECORD:
      return createNewSubrecord(state, action);
    case _record.DELETE_FIELD_VALUE:
      return deleteFieldValue(state, action);
    case _record.MOVE_FIELD_VALUE:
      return moveFieldValue(state, action);
    case _record.SET_FIELD_VALUE:
      return setFieldValue(state, action);
    case _record.FIELD_COMPUTE_FULFILLED:
      return handleFieldComputeFulfilled(state, action);
    case _record.RECORD_CREATED:
      return state.set(action.meta.newRecordCsid, state.get(action.meta.currentCsid)).delete(action.meta.currentCsid);
    case _record.RECORD_READ_STARTED:
      return state.setIn([action.meta.csid, 'isReadPending'], true);
    case _record.RECORD_READ_FULFILLED:
      return handleRecordReadFulfilled(state, action);
    case _record.RECORD_READ_REJECTED:
      return state.setIn([action.meta.csid, 'error'], _immutable2.default.fromJS(action.payload)).deleteIn([action.meta.csid, 'isReadPending']);
    case _record.RECORD_SAVE_STARTED:
      return state.setIn([action.meta.csid, 'isSavePending'], true);
    case _record.RECORD_SAVE_FULFILLED:
      return handleRecordSaveFulfilled(state, action);
    case _record.RECORD_SAVE_REJECTED:
      return state
      // I don't think there's any reason to store the save error.
      // .setIn([action.meta.csid, 'error'], Immutable.fromJS(action.payload))
      .deleteIn([action.meta.csid, 'isSavePending']);
    case _record.RECORD_TRANSITION_STARTED:
      return state.setIn([action.meta.csid, 'isSavePending'], true);
    case _record.RECORD_TRANSITION_FULFILLED:
      return handleTransitionFulfilled(state, action);
    case _record.RECORD_TRANSITION_REJECTED:
      return state.deleteIn([action.meta.csid, 'isSavePending']);
    case _record.SUBRECORD_CREATED:
      return handleSubrecordCreated(state, action);
    case _record.SUBRECORD_READ_FULFILLED:
      return state.setIn([action.meta.csid, 'subrecord', action.meta.subrecordName], action.meta.subrecordCsid);
    case _record.REVERT_RECORD:
      return revertRecord(state, action);
    case _relation.SUBJECT_RELATIONS_UPDATED:
      return handleSubjectRelationsUpdated(state, action);
    case _idGenerator.CREATE_ID_FULFILLED:
      return handleCreateIDFulfilled(state, action);
    case _record.DETACH_SUBRECORD:
      return detachSubrecord(state, action);
    case _login.LOGIN_FULFILLED:
      return clearAll(state);
    case _logout.LOGOUT_FULFILLED:
      return clearAll(state);
    default:
      return state;
  }
};

var getData = exports.getData = function getData(state, csid) {
  return getCurrentData(state, csid);
};

var getError = exports.getError = function getError(state, csid) {
  return state.getIn([csid, 'error']);
};

var getSubrecordCsid = exports.getSubrecordCsid = function getSubrecordCsid(state, csid, subrecordName) {
  return state.getIn([csid, 'subrecord', subrecordName]);
};

var getRelationUpdatedTimestamp = exports.getRelationUpdatedTimestamp = function getRelationUpdatedTimestamp(state, csid) {
  return state.getIn([csid, 'relationUpdatedTime']);
};

var getNewData = exports.getNewData = function getNewData(state) {
  return getData(state, unsavedRecordKey());
};

var getNewSubrecordCsid = exports.getNewSubrecordCsid = function getNewSubrecordCsid(state, subrecordName) {
  return getSubrecordCsid(state, unsavedRecordKey(), subrecordName);
};

var getValidationErrors = exports.getValidationErrors = function getValidationErrors(state, csid) {
  return state.getIn([csid, 'validation']);
};

var isReadPending = exports.isReadPending = function isReadPending(state, csid) {
  return state.getIn([csid, 'isReadPending']);
};

var isSavePending = exports.isSavePending = function isSavePending(state, csid) {
  return state.getIn([csid, 'isSavePending']);
};

var isModified = exports.isModified = function isModified(state, csid) {
  // Do a reference equality test between the current and baseline data. This will not detect if
  // a change is made, then another change is made that undoes the first. But it's more efficient
  // than a deep value equality test.

  if (getCurrentData(state, csid) !== getBaselineData(state, csid)) {
    return true;
  }

  // Check subrecords.

  var subrecords = state.getIn([csid, 'subrecord']);

  if (subrecords && subrecords.find(function (subrecordCsid) {
    return isModified(state, subrecordCsid);
  })) {
    return true;
  }

  return false;
};