'use strict';

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

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

var _get2 = _interopRequireDefault(_get);

var _upperFirst = require('lodash/upperFirst');

var _upperFirst2 = _interopRequireDefault(_upperFirst);

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

var _cspace2 = _interopRequireDefault(_cspace);

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

const transformDate = (input = {}) => {
  const output = {};

  output.dateDisplayDate = input.displayDate || null;
  output.scalarValuesComputed = input.scalarValuesComputed || null;

  ['earliestSingle', 'latest'].forEach(type => {
    const inputDate = input[`${type}Date`] || {};

    ['year', 'month', 'day', 'era', 'certainty', 'qualifier', 'qualifierValue', 'qualifierUnit'].forEach(field => {
      output[`date${(0, _upperFirst2.default)(type)}${(0, _upperFirst2.default)(field)}`] = inputDate[field] || null;
    });
  });

  return _immutable2.default.fromJS(output);
};

const parseDisplayDate = exports.parseDisplayDate = displayDate => () => {
  if (!displayDate) {
    return Promise.resolve({
      value: transformDate()
    });
  }

  const requestConfig = {
    params: {
      dateToParse: displayDate
    }
  };

  return (0, _cspace2.default)().read('structureddates', requestConfig).then(response => ({
    value: transformDate((0, _get2.default)(response, ['data', 'ns2:structureddate_common']))
  })).catch(() => ({
    isError: true
  }));
};

exports.default = {};