'use strict';

exports.__esModule = true;

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _moment = require('moment');

var _moment2 = _interopRequireDefault(_moment);

var _Input = require('../Input');

var _Input2 = _interopRequireDefault(_Input);

var _TimepickerDropdown = require('./TimepickerDropdown');

var _TimepickerDropdown2 = _interopRequireDefault(_TimepickerDropdown);

var _TimeSelector = require('./TimeSelector');

var _TimeSelector2 = _interopRequireDefault(_TimeSelector);

var _EventOverlay = require('../EventOverlay');

var _EventOverlay2 = _interopRequireDefault(_EventOverlay);

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

/**
 * @category controls
 * @component time-picker
 * @variations collab-ui-react
 */

var TimePicker = function (_React$Component) {
  (0, _inherits3.default)(TimePicker, _React$Component);

  function TimePicker() {
    var _temp, _this, _ret;

    (0, _classCallCheck3.default)(this, TimePicker);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
      isOpen: false,
      selectedTime: (0, _moment2.default)(_this.props.selectedTime),
      activeIndex: null,
      anchorNode: null
    }, _this.componentDidUpdate = function (prevProps, prevState) {
      var hourEntry = _this.hour;

      if (!prevState.isOpen && _this.state.isOpen) {
        _this.focusOnNode(hourEntry);
      }
    }, _this.focusOnNode = function (node) {
      node.focus();
    }, _this.hidePopover = function () {
      _this.setState({
        isOpen: false
      });
    }, _this.onFocus = function () {
      _this.setState({
        isOpen: true,
        anchorNode: _reactDom2.default.findDOMNode(_this.clickTextField).parentNode
      });
    }, _this.onMouseDown = function () {
      _this.setState({
        isOpen: !_this.state.isOpen,
        anchorNode: _reactDom2.default.findDOMNode(_this.clickTextField).parentNode
      });
    }, _this.triggerOnChange = function (dayChange) {
      _this.props.onChange && _this.props.onChange(_this.state.selectedTime.hour(), _this.state.selectedTime.minute(), dayChange);
    }, _this.changeTime = function (unit, change) {
      var newTime = (0, _moment2.default)(_this.state.selectedTime).add(change, unit);
      var dayChange = 0;

      if (change >= 0) {
        if (newTime.clone().startOf('day').isAfter((0, _moment2.default)().startOf('day'))) {
          newTime.add(-1, 'day');
          dayChange = 1;
        }
      } else {
        if (newTime.clone().startOf('day').isBefore((0, _moment2.default)().startOf('day'))) {
          newTime.add(1, 'day');
          dayChange = -1;
        }
      }

      _this.setState({ selectedTime: newTime }, _this.triggerOnChange(dayChange));
    }, _this.setTime = function (hour, minute, pre) {
      var meridianHour = pre === 'PM' && parseInt(hour) < 12 ? parseInt(hour) + 12 : pre === 'AM' && parseInt(hour) === 12 ? 0 : hour;

      _this.setState({
        selectedTime: _this.state.selectedTime.clone().hour(meridianHour).minute(minute)
      });
    }, _this.onSelectKeyDown = function (unit, e) {
      e.preventDefault();

      var _this$props = _this.props,
          minuteInterval = _this$props.minuteInterval,
          militaryTime = _this$props.militaryTime;

      var hour = !_this.hour.value && unit === 'h' ? militaryTime ? 0 : 1 : _this.hour.value;
      var minute = !_this.minute.value && unit === 'm' ? 0 : _this.minute.value;
      var pre = !militaryTime && _this.pre.value;

      if (e.keyCode === 65 && unit === 'pre') {
        if (_this.pre.value.includes('A')) return;

        return _this.changeTime('h', 12);
      } else if (e.keyCode === 80 && unit === 'pre') {
        if (_this.pre.value.includes('P')) return;

        return _this.changeTime('h', 12);
      } else if (e.keyCode === 38) {
        if (unit === 'pre') return _this.changeTime('h', 12);
        if (unit === 'h') return _this.changeTime('h', 1);

        return _this.changeTime(unit, minuteInterval);
      } else if (e.keyCode === 40) {
        if (unit === 'pre') return _this.changeTime('h', -12);
        if (unit === 'h') return _this.changeTime('h', -1);

        return _this.changeTime(unit, -minuteInterval);
      } else {
        _this.setTime(hour, minute, pre);
      }
    }, _this.onSelectWheel = function (unit, e) {
      if (e.deltaY < 0) {
        _this.changeTime(unit, 1);
      } else if (e.deltaY > 0) {
        _this.changeTime(unit, -1);
      }
      e.preventDefault();
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  // Jest does not handle DOM.focus(), this allows Jest to mock this function


  TimePicker.prototype.render = function render() {
    var _this2 = this;

    var _props = this.props,
        militaryTime = _props.militaryTime,
        minuteInterval = _props.minuteInterval;

    // Force the global locale onto our display moment

    var selectedMoment = this.state.selectedTime.locale(_moment2.default.locale());
    // Splits the moment string into seperate parts in order to add functionality to the TimePicker
    var timeString = militaryTime ? selectedMoment.format('HH:mm') : selectedMoment.format('LT');

    var hourText = selectedMoment.format(militaryTime ? 'HH' : 'hh');
    var minuteText = selectedMoment.format('mm');
    var postText = selectedMoment.format('A');

    var text = _react2.default.createElement(_Input2.default, {
      label: '',
      name: 'timepicker',
      htmlId: 'timepicker',
      onChange: function onChange() {},
      defaultValue: timeString,
      onMouseDown: this.onMouseDown,
      onFocus: this.onFocus,
      inputRef: function inputRef(ref) {
        return _this2.clickTextField = ref;
      },
      readOnly: true
    });

    var dropdownElement = _react2.default.createElement(
      _EventOverlay2.default,
      {
        allowClickAway: true,
        anchorNode: this.state.anchorNode,
        close: this.hidePopover,
        isOpen: this.state.isOpen },
      _react2.default.createElement(
        _TimepickerDropdown2.default,
        null,
        _react2.default.createElement(_TimeSelector2.default, {
          unit: 'h',
          min: 0,
          value: hourText,
          onWheel: this.onSelectWheel,
          inputRef: function inputRef(ref) {
            return _this2.hour = ref;
          },
          onKeyDown: this.onSelectKeyDown,
          onUpClick: function onUpClick() {
            return _this2.changeTime('h', 1);
          },
          onDownClick: function onDownClick() {
            return _this2.changeTime('h', -1);
          },
          militaryTime: militaryTime
        }),
        ':',
        _react2.default.createElement(_TimeSelector2.default, {
          unit: 'm',
          min: 0,
          value: minuteText,
          onWheel: this.onSelectWheel,
          inputRef: function inputRef(ref) {
            return _this2.minute = ref;
          },
          onKeyDown: this.onSelectKeyDown,
          onUpClick: function onUpClick() {
            return _this2.changeTime('m', minuteInterval);
          },
          onDownClick: function onDownClick() {
            return _this2.changeTime('m', -minuteInterval);
          }
        }),
        !militaryTime && _react2.default.createElement(_TimeSelector2.default, {
          unit: 'pre',
          value: postText,
          inputRef: function inputRef(ref) {
            return _this2.pre = ref;
          },
          onKeyDown: this.onSelectKeyDown,
          onWheel: this.onSelectWheel,
          onUpClick: function onUpClick() {
            return _this2.changeTime('h', 12);
          },
          onDownClick: function onDownClick() {
            return _this2.changeTime('h', -12);
          }
        })
      )
    );

    return _react2.default.createElement(
      'div',
      { className: 'cui-timepicker-container' },
      text,
      dropdownElement
    );
  };

  return TimePicker;
}(_react2.default.Component);

/**
* @name Default Time Picker
* @description Inputs are useful.
*
* @category controls
* @component time-picker
* @section default
*
* @js

import { Input } from '@collab-ui/react';

export default class Default extends React.PureComponent {
  render() {
    return (
      <div>
        <div className='timePicker-container'>
          <TimePicker
            selectedTime={new Date()}
          />
        </div>
      </div>
    );
  }
}

**/

/**
* @name Military Time Picker
* @description 24HR Time Picker
*
* @category controls
* @component time-picker
* @section 24-hour
*
* @js

import { Input } from '@collab-ui/react';

export default class Default extends React.PureComponent {
  render() {
    return (
      <div>
        <div className='timePicker-container'>
          <TimePicker
            selectedTime={new Date()}
            militaryTime
          />
        </div>
      </div>
    );
  }
}

**/

/**
* @name Step Time Picker
* @description Step Time Picker
*
* @category controls
* @component time-picker
* @section 30-minute-step
*
* @js

import { Input } from '@collab-ui/react';

export default class Default extends React.PureComponent {
  render() {
    return (
      <div>
        <div className='timePicker-container'>
          <TimePicker
            minuteInterval={30}
            selectedTime={new Date()}
          />
        </div>
      </div>
    );
  }
}

**/


TimePicker.displayName = 'TimePicker';
TimePicker.defaultProps = {
  militaryTime: false,
  className: '',
  minuteInterval: 1,
  onChange: null,
  selectedTime: null
};
exports.default = TimePicker;
module.exports = exports['default'];