"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createID = exports.readIDGenerator = exports.addIDGenerators = void 0;

var _session = _interopRequireDefault(require("../helpers/session"));

var _record = require("./record");

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

var _actionCodes = require("../constants/actionCodes");

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

const addIDGenerators = idGenerators => ({
  type: _actionCodes.ADD_ID_GENERATORS,
  payload: idGenerators
});

exports.addIDGenerators = addIDGenerators;

const readIDGenerator = idGeneratorName => (dispatch, getState) => {
  let idGeneratorCsid = null;
  const idGenerator = (0, _reducers.getIDGenerator)(getState(), idGeneratorName);

  if (idGenerator) {
    idGeneratorCsid = idGenerator.get('csid');
  }

  if (!idGeneratorCsid) {
    return null;
  }

  dispatch({
    type: _actionCodes.READ_ID_GENERATOR_STARTED,
    meta: {
      idGeneratorName
    }
  });
  const config = {
    params: {
      wf_deleted: false
    }
  };
  return (0, _session.default)().read(`idgenerators/${idGeneratorCsid}`, config).then(response => dispatch({
    type: _actionCodes.READ_ID_GENERATOR_FULFILLED,
    payload: response,
    meta: {
      idGeneratorName
    }
  })).catch(error => dispatch({
    type: _actionCodes.READ_ID_GENERATOR_REJECTED,
    payload: error,
    meta: {
      idGeneratorName
    }
  }));
};

exports.readIDGenerator = readIDGenerator;

const createID = (recordTypeConfig, idGeneratorName, csid, path, transform) => (dispatch, getState) => {
  let idGeneratorCsid = null;
  const idGenerator = (0, _reducers.getIDGenerator)(getState(), idGeneratorName);

  if (idGenerator) {
    idGeneratorCsid = idGenerator.get('csid');
  }

  if (!idGeneratorCsid) {
    return null;
  }

  dispatch({
    type: _actionCodes.CREATE_ID_STARTED,
    meta: {
      recordTypeConfig,
      idGeneratorName,
      csid,
      path
    }
  });
  return (0, _session.default)().create(`idgenerators/${idGeneratorCsid}/ids`).then(response => {
    dispatch({
      type: _actionCodes.CREATE_ID_FULFILLED,
      payload: response,
      meta: {
        recordTypeConfig,
        idGeneratorName,
        csid,
        path,
        transform
      }
    });
    return dispatch((0, _record.computeRecordData)(recordTypeConfig, csid)).then(() => dispatch((0, _record.validateRecordData)(recordTypeConfig, csid)));
  }).catch(error => dispatch({
    type: _actionCodes.CREATE_ID_REJECTED,
    payload: error,
    meta: {
      recordTypeConfig,
      idGeneratorName,
      csid,
      path
    }
  }));
};

exports.createID = createID;