'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.revertRecord = exports.setFieldValue = exports.moveFieldValue = exports.deleteFieldValue = exports.addFieldInstance = exports.saveRecord = exports.createNewRecord = exports.readRecord = exports.REVERT_RECORD = exports.SET_FIELD_VALUE = exports.MOVE_FIELD_VALUE = exports.DELETE_FIELD_VALUE = exports.ADD_FIELD_INSTANCE = exports.RECORD_SAVE_REJECTED = exports.RECORD_SAVE_FULFILLED = exports.RECORD_SAVE_STARTED = exports.RECORD_READ_REJECTED = exports.RECORD_READ_FULFILLED = exports.RECORD_READ_STARTED = exports.CREATE_NEW_RECORD = undefined;

var _cspace = require('./cspace');

var _cspace2 = _interopRequireDefault(_cspace);

var _reducers = require('../reducers');

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

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

var CREATE_NEW_RECORD = exports.CREATE_NEW_RECORD = 'CREATE_NEW_RECORD'; /* global window */

var RECORD_READ_STARTED = exports.RECORD_READ_STARTED = 'RECORD_READ_STARTED';
var RECORD_READ_FULFILLED = exports.RECORD_READ_FULFILLED = 'RECORD_READ_FULFILLED';
var RECORD_READ_REJECTED = exports.RECORD_READ_REJECTED = 'RECORD_READ_REJECTED';
var RECORD_SAVE_STARTED = exports.RECORD_SAVE_STARTED = 'RECORD_SAVE_STARTED';
var RECORD_SAVE_FULFILLED = exports.RECORD_SAVE_FULFILLED = 'RECORD_SAVE_FULFILLED';
var RECORD_SAVE_REJECTED = exports.RECORD_SAVE_REJECTED = 'RECORD_SAVE_REJECTED';
var ADD_FIELD_INSTANCE = exports.ADD_FIELD_INSTANCE = 'ADD_FIELD_INSTANCE';
var DELETE_FIELD_VALUE = exports.DELETE_FIELD_VALUE = 'DELETE_FIELD_VALUE';
var MOVE_FIELD_VALUE = exports.MOVE_FIELD_VALUE = 'MOVE_FIELD_VALUE';
var SET_FIELD_VALUE = exports.SET_FIELD_VALUE = 'SET_FIELD_VALUE';
var REVERT_RECORD = exports.REVERT_RECORD = 'REVERT_RECORD';

var doRead = function doRead(recordTypeConfig, vocabularyConfig, csid) {
  var recordServicePath = recordTypeConfig.serviceConfig.servicePath;

  var vocabularyServicePath = vocabularyConfig ? vocabularyConfig.serviceConfig.servicePath : null;

  var pathParts = [recordServicePath];

  if (vocabularyServicePath) {
    pathParts.push(vocabularyServicePath);
    pathParts.push('items');
  }

  pathParts.push(csid);

  var path = pathParts.join('/');

  var config = {
    params: {
      wf_deleted: false
    }
  };

  return (0, _cspace2.default)().read(path, config);
};

var readRecord = exports.readRecord = function readRecord(recordTypeConfig, vocabularyConfig, csid) {
  return function (dispatch) {
    dispatch({
      type: RECORD_READ_STARTED,
      meta: {
        recordTypeConfig: recordTypeConfig,
        csid: csid
      }
    });

    return doRead(recordTypeConfig, vocabularyConfig, csid).then(function (response) {
      return dispatch({
        type: RECORD_READ_FULFILLED,
        payload: response,
        meta: {
          recordTypeConfig: recordTypeConfig,
          csid: csid
        }
      });
    }).catch(function (error) {
      return dispatch({
        type: RECORD_READ_REJECTED,
        payload: error,
        meta: {
          recordTypeConfig: recordTypeConfig,
          csid: csid
        }
      });
    });
  };
};

var createNewRecord = exports.createNewRecord = function createNewRecord(recordTypeConfig, vocabularyConfig, cloneCsid) {
  return function (dispatch, getState) {
    var readClone = void 0;

    if (cloneCsid) {
      var data = (0, _reducers.getRecordData)(getState(), cloneCsid);

      if (!data) {
        // We don't have data for the record to be cloned. Read it first.

        readClone = dispatch(readRecord(recordTypeConfig, vocabularyConfig, cloneCsid));
      }
    }

    if (!readClone) {
      // There's nothing to clone, or we already have the record data to be cloned. Perform an
      // async noop, so this function will be consistently async.

      readClone = new Promise(function (resolve) {
        window.setTimeout(function () {
          resolve();
        }, 0);
      });
    }

    return readClone.then(function () {
      return dispatch({
        type: CREATE_NEW_RECORD,
        meta: {
          recordTypeConfig: recordTypeConfig,
          cloneCsid: cloneCsid
        }
      });
    });
  };
};

var saveRecord = exports.saveRecord = function saveRecord(recordTypeConfig, vocabularyConfig, csid, replace) {
  return function (dispatch, getState) {
    dispatch({
      type: RECORD_SAVE_STARTED,
      meta: {
        recordTypeConfig: recordTypeConfig,
        csid: csid
      }
    });

    var recordServicePath = recordTypeConfig.serviceConfig.servicePath;

    var vocabularyServicePath = vocabularyConfig ? vocabularyConfig.serviceConfig.servicePath : null;

    var pathParts = [recordServicePath];

    if (vocabularyServicePath) {
      pathParts.push(vocabularyServicePath);
      pathParts.push('items');
    }

    if (csid) {
      pathParts.push(csid);
    }

    var path = pathParts.join('/');

    var data = (0, _reducers.getRecordData)(getState(), csid);

    var config = {
      data: (0, _recordDataHelpers.prepareForSending)(data).toJS()
    };

    var savePromise = void 0;

    if (csid) {
      savePromise = (0, _cspace2.default)().update(path, config)
      // Need to read the record after update, because the update response doesn't include
      // collectionspace_core.
      .then(function () {
        return doRead(recordTypeConfig, vocabularyConfig, csid);
      }).then(function (response) {
        return dispatch({
          type: RECORD_SAVE_FULFILLED,
          payload: response,
          meta: {
            recordTypeConfig: recordTypeConfig,
            csid: csid
          }
        });
      });
    } else {
      savePromise = (0, _cspace2.default)().create(path, config).then(function (response) {
        if (response.status === 201 && response.headers.location) {
          // Redirect to the new record.

          var location = response.headers.location;
          var newRecordCsid = location.substring(location.lastIndexOf('/') + 1);

          var vocabularyPath = vocabularyConfig ? vocabularyConfig.name + '/' : '';

          replace('/record/' + recordTypeConfig.name + '/' + vocabularyPath + newRecordCsid);
        }

        return dispatch({
          type: RECORD_SAVE_FULFILLED,
          payload: response,
          meta: {
            recordTypeConfig: recordTypeConfig,
            csid: csid
          }
        });
      });
    }

    return savePromise.catch(function (error) {
      return dispatch({
        type: RECORD_SAVE_REJECTED,
        payload: error,
        meta: {
          recordTypeConfig: recordTypeConfig,
          csid: csid
        }
      });
    });
  };
};

var addFieldInstance = exports.addFieldInstance = function addFieldInstance(recordTypeConfig, csid, path) {
  return {
    type: ADD_FIELD_INSTANCE,
    meta: {
      csid: csid,
      path: path,
      recordTypeConfig: recordTypeConfig
    }
  };
};

var deleteFieldValue = exports.deleteFieldValue = function deleteFieldValue(csid, path) {
  return {
    type: DELETE_FIELD_VALUE,
    meta: {
      csid: csid,
      path: path
    }
  };
};

var moveFieldValue = exports.moveFieldValue = function moveFieldValue(csid, path, newPosition) {
  return {
    type: MOVE_FIELD_VALUE,
    meta: {
      csid: csid,
      path: path,
      newPosition: newPosition
    }
  };
};

var setFieldValue = exports.setFieldValue = function setFieldValue(csid, path, value) {
  return {
    type: SET_FIELD_VALUE,
    payload: value,
    meta: {
      csid: csid,
      path: path
    }
  };
};

var revertRecord = exports.revertRecord = function revertRecord(csid) {
  return {
    type: REVERT_RECORD,
    meta: {
      csid: csid
    }
  };
};