'use strict';

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

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; }; }();

require('react-day-picker/lib/style.css');

var _plotlyIcons = require('plotly-icons');

var _dates = require('plotly.js/src/lib/dates');

var _reactDayPicker = require('react-day-picker');

var _reactDayPicker2 = _interopRequireDefault(_reactDayPicker);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _TextInput2 = _interopRequireDefault(_TextInput);

var _Dropdown = require('./Dropdown');

var _Dropdown2 = _interopRequireDefault(_Dropdown);

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

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 testDate = '2000-01-01';
var testTime = '00:00';
var datePlaceholder = 'yyyy-mm-dd';
var timePlaceholder = 'hh:mm:ss.xxx';

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

  function DateTimePicker(props, context) {
    _classCallCheck(this, DateTimePicker);

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

    var _this$parsePlotlyJSDa = _this.parsePlotlyJSDateTime(props.value),
        time = _this$parsePlotlyJSDa.time,
        date = _this$parsePlotlyJSDa.date;

    var isValidTime = (0, _dates.isDateTime)(testDate + ' ' + time) || ['', timePlaceholder].includes(time);
    var isValidDate = (0, _dates.isDateTime)(date + ' ' + testTime) || ['', datePlaceholder].includes(date);

    _this.state = {
      calendarOpen: false,
      dateInputClassName: isValidDate ? 'datetimepicker-container-date-input' : 'datetimepicker-container-date-input +error',
      timeInputClassName: isValidTime ? 'datetimepicker-container-time-input' : 'datetimepicker-container-time-input +error',
      timeValue: time,
      dateValue: date,
      AMPM: _this.getAMPM(date, time, context.localize)
    };

    _this.toPlotlyJSDate = _this.toPlotlyJSDate.bind(_this);
    _this.onMonthChange = _this.onMonthChange.bind(_this);
    _this.onYearChange = _this.onYearChange.bind(_this);
    _this.onTimeChange = _this.onTimeChange.bind(_this);
    _this.onDateChange = _this.onDateChange.bind(_this);
    _this.onTimeUpdate = _this.onTimeUpdate.bind(_this);
    _this.onDateUpdate = _this.onDateUpdate.bind(_this);
    return _this;
  }

  _createClass(DateTimePicker, [{
    key: 'toPlotlyJSDate',
    value: function toPlotlyJSDate(value) {
      var ms = (0, _dates.dateTime2ms)(value);
      return (0, _dates.ms2DateTime)(ms);
    }
  }, {
    key: 'getYearOptions',
    value: function getYearOptions(current) {
      // eslint-disable-next-line
      var base = 5;
      var yearAsNumber = parseInt(current, 10);

      var lastFive = new Array(base).fill(0).map(function (year, index) {
        var newOption = yearAsNumber - (base - index);
        return { label: newOption, value: newOption };
      });

      var nextFive = new Array(base).fill(0).map(function (year, index) {
        var newOption = yearAsNumber + (index + 1);
        return { label: newOption, value: newOption };
      });

      return lastFive.concat([{ label: current, value: current }]).concat(nextFive);
    }
  }, {
    key: 'getMonthOptions',
    value: function getMonthOptions() {
      var _ = this.context.localize;
      return [{ label: _('January'), value: 0 }, { label: _('February'), value: 1 }, { label: _('March'), value: 2 }, { label: _('April'), value: 3 }, { label: _('May'), value: 4 }, { label: _('June'), value: 5 }, { label: _('July'), value: 6 }, { label: _('August'), value: 7 }, { label: _('September'), value: 8 }, { label: _('October'), value: 9 }, { label: _('November'), value: 10 }, { label: _('December'), value: 11 }];
    }
  }, {
    key: 'onMonthChange',
    value: function onMonthChange(value) {
      var currentDateInJS = new Date(this.getAdjustedPlotlyJSDateTime(this.props.value));
      currentDateInJS.setMonth(value);
      var plotlyJSDate = this.toPlotlyJSDate(currentDateInJS);

      if ((0, _dates.isDateTime)(plotlyJSDate)) {
        this.props.onChange(plotlyJSDate);
      }

      var _parsePlotlyJSDateTim = this.parsePlotlyJSDateTime(plotlyJSDate),
          time = _parsePlotlyJSDateTim.time,
          date = _parsePlotlyJSDateTim.date;

      this.setState({
        timeValue: time,
        dateValue: date
      });
    }
  }, {
    key: 'onYearChange',
    value: function onYearChange(value) {
      var currentDateInJS = new Date(this.getAdjustedPlotlyJSDateTime(this.props.value));
      currentDateInJS.setFullYear(value);
      var plotlyJSDate = this.toPlotlyJSDate(currentDateInJS);

      if ((0, _dates.isDateTime)(plotlyJSDate)) {
        this.props.onChange(plotlyJSDate);
      }

      var _parsePlotlyJSDateTim2 = this.parsePlotlyJSDateTime(plotlyJSDate),
          time = _parsePlotlyJSDateTim2.time,
          date = _parsePlotlyJSDateTim2.date;

      this.setState({
        timeValue: time,
        dateValue: date
      });
    }
  }, {
    key: 'parsePlotlyJSDateTime',
    value: function parsePlotlyJSDateTime(value) {
      var parsed = value.split(' ');
      return { date: parsed[0], time: parsed[1] ? parsed[1] : '' };
    }
  }, {
    key: 'getAMPM',
    value: function getAMPM(date, time, _) {
      var plotlyJSDateTime = date + ' ' + time;
      var isValidDateTime = (0, _dates.isDateTime)(plotlyJSDateTime);
      var JSDate = new Date(this.getAdjustedPlotlyJSDateTime(plotlyJSDateTime));
      var localeTime = JSDate.toLocaleTimeString('en-US').split(' ');

      var parsedTime = time.split(':').reduce(function (timeArray, timePart) {
        var parsed = timePart.split('.');
        return timeArray.concat(parsed);
      }, []);

      var isNoon = parsedTime[0] === '12' && parsedTime.slice(1).every(function (part) {
        return parseInt(part, 10) === 0;
      });

      return !isValidDateTime || time === '' || JSDate.toDateString() === 'Invalid Date' ? '' : localeTime[1] === 'PM' ? isNoon ? _('noon') : 'PM' : 'AM';
    }
  }, {
    key: 'adjustedTime',
    value: function adjustedTime(time) {
      if (time.toString().length <= 2) {
        return time + ':00';
      }
      return time;
    }
  }, {
    key: 'onTimeChange',
    value: function onTimeChange(value) {
      var _parsePlotlyJSDateTim3 = this.parsePlotlyJSDateTime(this.props.value),
          currentDate = _parsePlotlyJSDateTim3.date;

      var isValidTime = (0, _dates.isDateTime)(testDate + ' ' + value);

      this.setState({
        timeInputClassName: isValidTime || value === '' ? 'datetimepicker-container-time-input' : 'datetimepicker-container-time-input +error',
        timeValue: value,
        AMPM: this.getAMPM(currentDate, value, this.context.localize)
      });
    }
  }, {
    key: 'onDateChange',
    value: function onDateChange(value) {
      var isValidDate = (0, _dates.isDateTime)(value + ' ' + testTime);
      this.setState({
        dateInputClassName: isValidDate || value === '' ? 'datetimepicker-container-date-input' : 'datetimepicker-container-date-input +error',
        dateValue: value
      });
    }
  }, {
    key: 'onTimeUpdate',
    value: function onTimeUpdate(value) {
      var _parsePlotlyJSDateTim4 = this.parsePlotlyJSDateTime(this.props.value),
          currentTime = _parsePlotlyJSDateTim4.time,
          currentDate = _parsePlotlyJSDateTim4.date;

      var isValidTime = (0, _dates.isDateTime)(testDate + ' ' + value);

      if (value === '') {
        this.setState({
          timeInputClassName: 'datetimepicker-container-time-input',
          timeValue: currentTime,
          AMPM: this.getAMPM(currentDate, currentTime, this.context.localize)
        });
        return;
      }

      if (isValidTime) {
        this.props.onChange(currentDate + ' ' + value);
      }
    }
  }, {
    key: 'onDateUpdate',
    value: function onDateUpdate(value) {
      var _parsePlotlyJSDateTim5 = this.parsePlotlyJSDateTime(this.props.value),
          currentDate = _parsePlotlyJSDateTim5.date,
          currentTime = _parsePlotlyJSDateTim5.time;

      var isValidDate = (0, _dates.isDateTime)(value + ' ' + testTime);

      if (isValidDate) {
        this.props.onChange(value + ' ' + currentTime);
        return;
      }

      if (value === '') {
        this.setState({
          dateValue: currentDate,
          dateInputClassName: 'datetimepicker-container-date-input'
        });
        return;
      }
    }
  }, {
    key: 'getAdjustedPlotlyJSDateTime',
    value: function getAdjustedPlotlyJSDateTime(dateTimeString) {
      var _parsePlotlyJSDateTim6 = this.parsePlotlyJSDateTime(dateTimeString),
          date = _parsePlotlyJSDateTim6.date,
          time = _parsePlotlyJSDateTim6.time;

      return date + ' ' + this.adjustedTime(time);
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var JSDate = new Date(this.getAdjustedPlotlyJSDateTime(this.state.dateValue + ' ' + testTime));
      var isValidJSDate = JSDate.toDateString() !== 'Invalid Date';
      var currentYear = isValidJSDate ? JSDate.getFullYear() : new Date().getFullYear();
      var currentMonth = isValidJSDate ? JSDate.getMonth() : new Date().getMonth();

      return _react2.default.createElement(
        'div',
        { className: 'datetimepicker-container' },
        _react2.default.createElement(_TextInput2.default, {
          value: this.state.dateValue,
          editableClassName: this.state.dateInputClassName,
          onChange: this.onDateChange,
          onUpdate: this.onDateUpdate,
          placeholder: datePlaceholder
        }),
        _react2.default.createElement(
          'div',
          { className: 'datetimepicker-container-icons' },
          _react2.default.createElement(_plotlyIcons.CalendarMultiselectIcon, {
            onClick: function onClick() {
              return _this2.setState({ calendarOpen: !_this2.state.calendarOpen });
            },
            className: this.state.calendarOpen ? 'datetimepicker-date-icon--selected' : 'datetimepicker-date-icon'
          })
        ),
        this.state.calendarOpen ? _react2.default.createElement(
          'div',
          { className: 'datetimepicker-container__content' },
          this.state.calendarOpen ? _react2.default.createElement(
            'div',
            { className: 'datetimepicker-datepicker-container' },
            _react2.default.createElement(
              'div',
              { className: 'datetimepicker-datepicker-navbar' },
              _react2.default.createElement(_Dropdown2.default, {
                options: this.getMonthOptions(),
                value: currentMonth,
                className: 'datimepicker-monthpicker',
                clearable: false,
                onChange: this.onMonthChange
              }),
              _react2.default.createElement(_Dropdown2.default, {
                options: this.getYearOptions(currentYear),
                value: currentYear,
                className: 'datimepicker-yearpicker',
                clearable: false,
                onChange: this.onYearChange
              })
            ),
            _react2.default.createElement(_reactDayPicker2.default, {
              className: 'datepicker-container-rce',
              modifiers: { highlighted: isValidJSDate ? JSDate : '' },
              month: isValidJSDate ? JSDate : new Date(),
              onDayClick: function onDayClick(value) {
                var plotlyDate = _this2.toPlotlyJSDate(value).split(' ')[0];
                _this2.onDateChange(plotlyDate);
                _this2.onDateUpdate(plotlyDate);
              }
            })
          ) : null
        ) : null,
        _react2.default.createElement(
          'div',
          { className: 'datetimepicker-container-time' },
          _react2.default.createElement(_TextInput2.default, {
            value: this.state.timeValue,
            onChange: this.onTimeChange,
            onUpdate: this.onTimeUpdate,
            placeholder: timePlaceholder,
            editableClassName: this.state.timeInputClassName
          }),
          _react2.default.createElement(
            'span',
            { className: 'datetimepicker-date-units' },
            this.state.AMPM
          )
        )
      );
    }
  }]);

  return DateTimePicker;
}(_react.Component);

exports.default = DateTimePicker;


DateTimePicker.propTypes = {
  value: _propTypes2.default.string.isRequired,
  onChange: _propTypes2.default.func.isRequired
};

DateTimePicker.contextTypes = {
  localize: _propTypes2.default.func
};
//# sourceMappingURL=DateTimePicker.js.map