'use strict';

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

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _cspaceLayout = require('cspace-layout');

var _set = require('lodash/set');

var _set2 = _interopRequireDefault(_set);

var _merge = require('lodash/merge');

var _merge2 = _interopRequireDefault(_merge);

var _CustomCompoundInput = require('./CustomCompoundInput');

var _CustomCompoundInput2 = _interopRequireDefault(_CustomCompoundInput);

var _DropdownInput = require('./DropdownInput');

var _DropdownInput2 = _interopRequireDefault(_DropdownInput);

var _Label = require('./Label');

var _Label2 = _interopRequireDefault(_Label);

var _TextInput = require('./TextInput');

var _TextInput2 = _interopRequireDefault(_TextInput);

var _PrefixFilteringDropdownMenuInput = require('./PrefixFilteringDropdownMenuInput');

var _PrefixFilteringDropdownMenuInput2 = _interopRequireDefault(_PrefixFilteringDropdownMenuInput);

var _VocabularyControlledInput = require('./VocabularyControlledInput');

var _VocabularyControlledInput2 = _interopRequireDefault(_VocabularyControlledInput);

var _changeable = require('../enhancers/changeable');

var _changeable2 = _interopRequireDefault(_changeable);

var _committable = require('../enhancers/committable');

var _committable2 = _interopRequireDefault(_committable);

var _withLabeledOptions = require('../enhancers/withLabeledOptions');

var _withLabeledOptions2 = _interopRequireDefault(_withLabeledOptions);

var _labelable = require('../enhancers/labelable');

var _labelable2 = _interopRequireDefault(_labelable);

var _pathHelpers = require('../helpers/pathHelpers');

var _dateHelpers = require('../helpers/dateHelpers');

var _StructuredDateInput = require('../../styles/cspace-input/StructuredDateInput.css');

var _StructuredDateInput2 = _interopRequireDefault(_StructuredDateInput);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DropdownInput = (0, _committable2.default)((0, _changeable2.default)(_DropdownInput2.default));
var TextInput = (0, _committable2.default)((0, _changeable2.default)(_TextInput2.default));
var LabelableTextInput = (0, _labelable2.default)(TextInput);
var PrefixFilteringDropdownMenuInput = (0, _withLabeledOptions2.default)(_PrefixFilteringDropdownMenuInput2.default);

var primaryFieldName = 'dateDisplayDate';

var getStructDateFieldValue = function getStructDateFieldValue(structDateValue, fieldName) {
  if (!structDateValue) {
    return undefined;
  }

  if (_immutable2.default.Map.isMap(structDateValue)) {
    return structDateValue.get(fieldName);
  }

  return structDateValue[fieldName];
};

var getPrimaryValue = function getPrimaryValue(structDateValue) {
  return getStructDateFieldValue(structDateValue, primaryFieldName);
};

var fieldLabels = {
  earliestSingle: 'Earliest/Single',
  latest: 'Latest',
  datePeriod: 'Period',
  dateAssociation: 'Association',
  dateNote: 'Note',
  dateYear: 'Year',
  dateMonth: 'Month',
  dateDay: 'Day',
  dateEra: 'Era',
  dateCertainty: 'Certainty',
  dateQualifier: 'Qualifier',
  dateQualifierValue: 'Value',
  dateQualifierUnit: 'Unit'
};

var propTypes = {
  defaultValue: _react.PropTypes.oneOfType([_react.PropTypes.object, // eslint-disable-line react/forbid-prop-types
  _react.PropTypes.instanceOf(_immutable2.default.Map)]),
  embedded: _react.PropTypes.bool,
  formatFieldLabel: _react.PropTypes.func,
  formatOptionLabel: _react.PropTypes.func,
  name: _react.PropTypes.string,
  optionLists: _react.PropTypes.object,
  parentPath: _pathHelpers.pathPropType,
  subpath: _pathHelpers.pathPropType,
  terms: _react.PropTypes.object,
  value: _react.PropTypes.oneOfType([_react.PropTypes.object, // eslint-disable-line react/forbid-prop-types
  _react.PropTypes.instanceOf(_immutable2.default.Map)]),
  onCommit: _react.PropTypes.func,
  onMount: _react.PropTypes.func
};

var defaultProps = {
  defaultValue: {},
  formatFieldLabel: function formatFieldLabel(name) {
    return fieldLabels[name];
  },
  optionLists: {},
  terms: {}
};

var StructuredDateInput = function (_Component) {
  _inherits(StructuredDateInput, _Component);

  function StructuredDateInput(props) {
    _classCallCheck(this, StructuredDateInput);

    var _this = _possibleConstructorReturn(this, (StructuredDateInput.__proto__ || Object.getPrototypeOf(StructuredDateInput)).call(this, props));

    _this.handleDropdownInputClose = _this.handleDropdownInputClose.bind(_this);
    _this.handleDropdownInputOpen = _this.handleDropdownInputOpen.bind(_this);
    _this.handleInputCommit = _this.handleInputCommit.bind(_this);
    _this.handlePrimaryInputChange = _this.handlePrimaryInputChange.bind(_this);
    _this.handlePrimaryInputCommit = _this.handlePrimaryInputCommit.bind(_this);

    var value = props.value || props.defaultValue;

    _this.state = {
      value: value,
      open: false,
      primaryValue: getPrimaryValue(value)
    };
    return _this;
  }

  _createClass(StructuredDateInput, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var onMount = this.props.onMount;


      if (onMount) {
        onMount();
      }
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var value = nextProps.value || nextProps.defaultValue;

      this.setState({
        value: value,
        primaryValue: getPrimaryValue(value)
      });
    }
  }, {
    key: 'getValue',
    value: function getValue(name) {
      var value = this.state.value;


      return getStructDateFieldValue(value, name);
    }
  }, {
    key: 'setValue',
    value: function setValue(path, value) {
      var structDateValue = this.state.value;


      var newStructDateValue = void 0;

      if (_immutable2.default.Map.isMap(structDateValue)) {
        newStructDateValue = structDateValue.setIn(path, value);

        var newStructDateValueAsObject = newStructDateValue.toJS();
        var dateEarliestScalarValue = (0, _dateHelpers.computeEarliestScalarDate)(newStructDateValueAsObject);
        var dateLatestScalarValue = (0, _dateHelpers.computeLatestScalarDate)(newStructDateValueAsObject);

        newStructDateValue = newStructDateValue.set('dateEarliestScalarValue', dateEarliestScalarValue);
        newStructDateValue = newStructDateValue.set('dateLatestScalarValue', dateLatestScalarValue);
        newStructDateValue = newStructDateValue.set('scalarValuesComputed', true);
      } else {
        newStructDateValue = (0, _merge2.default)({}, structDateValue);
        (0, _set2.default)(newStructDateValue, path, value);

        var _dateEarliestScalarValue = (0, _dateHelpers.computeEarliestScalarDate)(newStructDateValue);
        var _dateLatestScalarValue = (0, _dateHelpers.computeLatestScalarDate)(newStructDateValue);

        newStructDateValue.dateEarliestScalarValue = _dateEarliestScalarValue;
        newStructDateValue.dateLatestScalarValue = _dateLatestScalarValue;
        newStructDateValue.scalarValuesComputed = true;
      }

      return newStructDateValue;
    }
  }, {
    key: 'handleDropdownInputClose',
    value: function handleDropdownInputClose() {
      this.setState({
        open: false
      });
    }
  }, {
    key: 'handleDropdownInputOpen',
    value: function handleDropdownInputOpen() {
      this.setState({
        open: true
      });
    }
  }, {
    key: 'handleInputCommit',
    value: function handleInputCommit(path, value) {
      var newStructDateValue = this.setValue(path, value);

      var onCommit = this.props.onCommit;


      if (onCommit) {
        onCommit((0, _pathHelpers.getPath)(this.props), newStructDateValue);
      }

      this.setState({
        value: newStructDateValue
      });
    }
  }, {
    key: 'handlePrimaryInputCommit',
    value: function handlePrimaryInputCommit(path, value) {
      var initialValue = this.getValue(primaryFieldName);

      if ((value || initialValue) && value !== initialValue) {
        this.handleInputCommit([primaryFieldName], value);
      }
    }
  }, {
    key: 'handlePrimaryInputChange',
    value: function handlePrimaryInputChange(value) {
      this.setState({
        open: true,
        primaryValue: value
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          formatFieldLabel = _props.formatFieldLabel,
          formatOptionLabel = _props.formatOptionLabel,
          optionLists = _props.optionLists,
          terms = _props.terms,
          defaultValue = _props.defaultValue,
          name = _props.name,
          parentPath = _props.parentPath,
          subpath = _props.subpath,
          valueProp = _props.value,
          onCommit = _props.onCommit,
          onMount = _props.onMount,
          remainingProps = _objectWithoutProperties(_props, ['formatFieldLabel', 'formatOptionLabel', 'optionLists', 'terms', 'defaultValue', 'name', 'parentPath', 'subpath', 'value', 'onCommit', 'onMount']);

      var _state = this.state,
          open = _state.open,
          primaryValue = _state.primaryValue,
          value = _state.value;


      return _react2.default.createElement(
        DropdownInput,
        _extends({}, remainingProps, {
          className: _StructuredDateInput2.default.normal,
          commitUnchanged: true,
          open: open,
          value: primaryValue,
          onChange: this.handlePrimaryInputChange,
          onClose: this.handleDropdownInputClose,
          onCommit: this.handlePrimaryInputCommit,
          onOpen: this.handleDropdownInputOpen
        }),
        _react2.default.createElement(
          _CustomCompoundInput2.default,
          { value: value },
          _react2.default.createElement(
            _cspaceLayout.Row,
            null,
            _react2.default.createElement(
              'div',
              null,
              _react2.default.createElement(LabelableTextInput, {
                name: 'datePeriod',
                label: formatFieldLabel('datePeriod'),
                onCommit: this.handleInputCommit
              })
            ),
            _react2.default.createElement(
              'div',
              null,
              _react2.default.createElement(LabelableTextInput, {
                name: 'dateAssociation',
                label: formatFieldLabel('dateAssociation'),
                onCommit: this.handleInputCommit
              })
            ),
            _react2.default.createElement(
              'div',
              null,
              _react2.default.createElement(LabelableTextInput, {
                name: 'dateNote',
                label: formatFieldLabel('dateNote'),
                onCommit: this.handleInputCommit
              })
            )
          ),
          _react2.default.createElement(
            'table',
            null,
            _react2.default.createElement(
              'thead',
              null,
              _react2.default.createElement(
                'tr',
                null,
                _react2.default.createElement('th', null),
                _react2.default.createElement(
                  'th',
                  null,
                  _react2.default.createElement(
                    _Label2.default,
                    null,
                    formatFieldLabel('dateYear')
                  )
                ),
                _react2.default.createElement(
                  'th',
                  null,
                  _react2.default.createElement(
                    _Label2.default,
                    null,
                    formatFieldLabel('dateMonth')
                  )
                ),
                _react2.default.createElement(
                  'th',
                  null,
                  _react2.default.createElement(
                    _Label2.default,
                    null,
                    formatFieldLabel('dateDay')
                  )
                ),
                _react2.default.createElement(
                  'th',
                  null,
                  _react2.default.createElement(
                    _Label2.default,
                    null,
                    formatFieldLabel('dateEra')
                  )
                ),
                _react2.default.createElement(
                  'th',
                  null,
                  _react2.default.createElement(
                    _Label2.default,
                    null,
                    formatFieldLabel('dateCertainty')
                  )
                ),
                _react2.default.createElement(
                  'th',
                  null,
                  _react2.default.createElement(
                    _Label2.default,
                    null,
                    formatFieldLabel('dateQualifier')
                  )
                ),
                _react2.default.createElement(
                  'th',
                  null,
                  _react2.default.createElement(
                    _Label2.default,
                    null,
                    formatFieldLabel('dateQualifierValue')
                  )
                ),
                _react2.default.createElement(
                  'th',
                  null,
                  _react2.default.createElement(
                    _Label2.default,
                    null,
                    formatFieldLabel('dateQualifierUnit')
                  )
                )
              )
            ),
            _react2.default.createElement(
              'tbody',
              null,
              _react2.default.createElement(
                'tr',
                null,
                _react2.default.createElement(
                  'th',
                  null,
                  _react2.default.createElement(
                    _Label2.default,
                    null,
                    formatFieldLabel('earliestSingle')
                  )
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(TextInput, {
                    embedded: true,
                    name: 'dateEarliestSingleYear',
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(TextInput, {
                    embedded: true,
                    name: 'dateEarliestSingleMonth',
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(TextInput, {
                    embedded: true,
                    name: 'dateEarliestSingleDay',
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(_VocabularyControlledInput2.default, {
                    embedded: true,
                    name: 'dateEarliestSingleEra',
                    terms: terms.dateera,
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(_VocabularyControlledInput2.default, {
                    embedded: true,
                    name: 'dateEarliestSingleCertainty',
                    terms: terms.datecertainty,
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(PrefixFilteringDropdownMenuInput, {
                    embedded: true,
                    formatOptionLabel: formatOptionLabel,
                    name: 'dateEarliestSingleQualifier',
                    options: optionLists.dateQualifiers,
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(TextInput, {
                    embedded: true,
                    name: 'dateEarliestSingleQualifierValue',
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(_VocabularyControlledInput2.default, {
                    embedded: true,
                    name: 'dateEarliestSingleQualifierUnit',
                    terms: terms.datequalifier,
                    onCommit: this.handleInputCommit
                  })
                )
              ),
              _react2.default.createElement(
                'tr',
                null,
                _react2.default.createElement(
                  'th',
                  null,
                  _react2.default.createElement(
                    _Label2.default,
                    null,
                    formatFieldLabel('latest')
                  )
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(TextInput, {
                    embedded: true,
                    name: 'dateLatestYear',
                    value: this.getValue('dateLatestYear'),
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(TextInput, {
                    embedded: true,
                    name: 'dateLatestMonth',
                    value: this.getValue('dateLatestMonth'),
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(TextInput, {
                    embedded: true,
                    name: 'dateLatestDay',
                    value: this.getValue('dateLatestDay'),
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(_VocabularyControlledInput2.default, {
                    embedded: true,
                    name: 'dateLatestEra',
                    terms: terms.dateera,
                    value: this.getValue('dateLatestEra'),
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(_VocabularyControlledInput2.default, {
                    embedded: true,
                    name: 'dateLatestCertainty',
                    terms: terms.datecertainty,
                    value: this.getValue('dateLatestCertainty'),
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(PrefixFilteringDropdownMenuInput, {
                    embedded: true,
                    formatOptionLabel: formatOptionLabel,
                    name: 'dateLatestQualifier',
                    options: optionLists.dateQualifiers,
                    value: this.getValue('dateLatestQualifier'),
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(TextInput, {
                    embedded: true,
                    name: 'dateLatestQualifierValue',
                    value: this.getValue('dateLatestQualifierValue'),
                    onCommit: this.handleInputCommit
                  })
                ),
                _react2.default.createElement(
                  'td',
                  null,
                  _react2.default.createElement(_VocabularyControlledInput2.default, {
                    embedded: true,
                    name: 'dateLatestQualifierUnit',
                    terms: terms.datequalifier,
                    value: this.getValue('dateLatestQualifierUnit'),
                    onCommit: this.handleInputCommit
                  })
                )
              )
            )
          )
        )
      );
    }
  }]);

  return StructuredDateInput;
}(_react.Component);

exports.default = StructuredDateInput;


StructuredDateInput.propTypes = propTypes;
StructuredDateInput.defaultProps = defaultProps;