"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.sectionRange = exports.sectionTitle = exports.sidebarSection = exports.default = exports.DatePicker = exports._internal = exports.languageToDateFormat = void 0;

var R = _interopRequireWildcard(require("ramda"));

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames = _interopRequireDefault(require("classnames"));

var _Button = require("../Button");

var _ErrorBoundary = require("../ErrorBoundary");

var _luxon = require("luxon");

var _reactDateRange = require("react-date-range");

require("react-date-range/dist/styles.css");

require("react-date-range/dist/theme/default.css");

var _locale = require("react-date-range/dist/locale");

require("./DatePicker.css");

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

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

function _extends() { _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; }; return _extends.apply(this, arguments); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function SidebarRangeSection(_ref) {
  var config = _ref.config,
      selectedId = _ref.selectedId,
      onRangeSelect = _ref.onRangeSelect;
  var title = config.title,
      ranges = config.ranges;
  return _react.default.createElement(_react.default.Fragment, null, _react.default.createElement("h4", {
    className: "date-range-title"
  }, title), _react.default.createElement("ul", null, ranges.map(function (_ref2) {
    var id = _ref2.id,
        label = _ref2.label;
    return _react.default.createElement("li", {
      key: id
    }, _react.default.createElement("span", {
      className: id,
      onClick: function onClick() {
        return onRangeSelect(id);
      }
    }, _react.default.createElement("input", {
      type: "radio",
      onChange: function onChange() {
        return onRangeSelect(id);
      },
      checked: selectedId === id
    }), label));
  })));
}

var rangeConfigShape = _propTypes.default.shape({
  title: _propTypes.default.string,
  ranges: _propTypes.default.arrayOf(_propTypes.default.shape({
    id: _propTypes.default.string,
    label: _propTypes.default.string
  }))
});

SidebarRangeSection.propTypes = {
  config: rangeConfigShape,
  onRangeSelect: _propTypes.default.func,
  selectedId: _propTypes.default.string
};
var applyRange = R.flip(R.cond([[R.is(Function), R.call], [R.is(Array), R.identity], [R.T, function (_, selectedRanges, idx) {
  return selectedRanges[idx];
}]]));

var rangeFor = function rangeFor(_ref3, selected) {
  var ranges = _ref3.ranges;
  return R.prop('range', R.find(R.propEq('id', selected), ranges));
};

var getIndex = function getIndex(_, __, v) {
  return v;
};

var getAccumulator = function getAccumulator(v) {
  return v;
};

var applyRangeSpecs = R.addIndex(R.reduce)(R.converge(R.update, [getIndex, applyRange, getAccumulator]));
var doSidebarRangeSelect = R.curry(function (rangeConfigs, selectedNamedRanges, updateNamedCalendarRanges, updateCalendarRanges, selectedRanges, index, selection) {
  var newSelectedNamedRanges = R.update(index, selection, selectedNamedRanges);
  var newSelectedRanges = applyRangeSpecs(selectedRanges, R.zipWith(rangeFor, rangeConfigs, newSelectedNamedRanges));
  updateCalendarRanges(newSelectedRanges);
  updateNamedCalendarRanges(newSelectedNamedRanges);
});

var DatePickerSidebar = function DatePickerSidebar(_ref4) {
  var rangeConfig = _ref4.rangeConfig,
      selectedSidebarRanges = _ref4.selectedSidebarRanges,
      onNamedRangeSelect = _ref4.onNamedRangeSelect;
  return _react.default.createElement("div", {
    className: 'vs-date-picker-sidebar'
  }, R.addIndex(R.zipWith)(function (config, selected, index) {
    return _react.default.createElement(SidebarRangeSection, {
      key: config.title,
      config: config,
      selectedId: selected,
      onRangeSelect: onNamedRangeSelect(index)
    });
  }, rangeConfig, selectedSidebarRanges));
};

DatePickerSidebar.propTypes = {
  onNamedRangeSelect: _propTypes.default.func,
  rangeConfig: _propTypes.default.arrayOf(_propTypes.default.shape({
    title: _propTypes.default.string,
    ranges: _propTypes.default.array
  })),
  selectedSidebarRanges: _propTypes.default.arrayOf(_propTypes.default.string),
  comparisonRanges: _propTypes.default.arrayOf(_propTypes.default.array)
};
var languageToLocale = {
  cs: _locale.cs,
  de: _locale.de,
  en: _locale.enUS,
  es: _locale.es,
  fr: _locale.fr,
  pl: _locale.pl,
  zh: _locale.zhCN,
  ja: _locale.ja,
  pt: _locale.pt
};
var languageToDateFormat = {
  cs: 'D. MMMM YYYY',
  de: 'D. MMMM YYYY',
  en: 'MMMM D, YYYY',
  es: 'D [de] MMMM [de] YYYY',
  fr: 'D MMMM YYYY',
  pl: 'D MMMM YYYY',
  zh: 'YYYY年MMMMD日',
  pt: 'D [de] MMMM [de] YYYY',
  ja: 'YYYY年M月D日'
};
exports.languageToDateFormat = languageToDateFormat;
var internalDateFormat = 'yyyy-MM-dd';

function fromInternalDateFormat(date) {
  return _luxon.DateTime.fromFormat(date, internalDateFormat).toLocal();
}

var _internal = {
  internalDateFormat: internalDateFormat,
  fromInternalDateFormat: fromInternalDateFormat
};
exports._internal = _internal;

var rangeToCalendarInput = function rangeToCalendarInput(range, intervalColor) {
  return {
    startDate: range[0] && fromInternalDateFormat(range[0]).toJSDate(),
    endDate: range[1] && fromInternalDateFormat(range[1]).toJSDate(),
    range1: range,
    color: intervalColor
  };
};

function updateSelectedRanges(idx, newRange, selectedRanges) {
  return R.update(idx, R.map(function (v) {
    return v && _luxon.DateTime.fromJSDate(v).toFormat('yyyy-MM-dd');
  }, newRange), selectedRanges);
}

var adaptToReactDateRange = function adaptToReactDateRange(intervalColors, intervals, namedIntervals) {
  var result = R.zipWith(rangeToCalendarInput, intervals, intervalColors);
  result = R.zipWith(function (range, interval) {
    return interval === 'none' ? null : range;
  }, result, namedIntervals);
  return R.filter(R.identity, result);
};

var DatePicker = function DatePicker(_ref5) {
  var updateCalendarRanges = _ref5.updateCalendarRanges,
      updateNamedCalendarRanges = _ref5.updateNamedCalendarRanges,
      onApply = _ref5.onApply,
      _ref5$onCancel = _ref5.onCancel,
      onCancel = _ref5$onCancel === void 0 ? function () {} : _ref5$onCancel,
      _ref5$selectableRange = _slicedToArray(_ref5.selectableRange, 2),
      minDate = _ref5$selectableRange[0],
      maxDate = _ref5$selectableRange[1],
      selectedRanges = _ref5.selectedRanges,
      selectedNamedRanges = _ref5.selectedNamedRanges,
      sidebarConfig = _ref5.sidebarConfig,
      _ref5$cancelButtonTex = _ref5.cancelButtonText,
      cancelButtonText = _ref5$cancelButtonTex === void 0 ? 'Cancel' : _ref5$cancelButtonTex,
      _ref5$applyButtonText = _ref5.applyButtonText,
      applyButtonText = _ref5$applyButtonText === void 0 ? 'Apply' : _ref5$applyButtonText,
      _ref5$locale = _ref5.locale,
      locale = _ref5$locale === void 0 ? 'en' : _ref5$locale,
      _ref5$dateFormat = _ref5.dateFormat,
      dateFormat = _ref5$dateFormat === void 0 ? languageToDateFormat[locale] : _ref5$dateFormat,
      _ref5$intervalColors = _ref5.intervalColors,
      intervalColors = _ref5$intervalColors === void 0 ? ['#05afec', '#0061ac'] : _ref5$intervalColors,
      className = _ref5.className,
      restProps = _objectWithoutProperties(_ref5, ["updateCalendarRanges", "updateNamedCalendarRanges", "onApply", "onCancel", "selectableRange", "selectedRanges", "selectedNamedRanges", "sidebarConfig", "cancelButtonText", "applyButtonText", "locale", "dateFormat", "intervalColors", "className"]);

  var rangeSelectHandler = doSidebarRangeSelect(sidebarConfig, selectedNamedRanges, updateNamedCalendarRanges, updateCalendarRanges);
  var calendarRangeInput = adaptToReactDateRange(intervalColors, selectedRanges, selectedNamedRanges);
  return _react.default.createElement("div", _extends({}, restProps, {
    className: (0, _classnames.default)(className, 'vs-date-picker', {
      'vs-date-picker-side-by-side': R.length(calendarRangeInput) === 2
    })
  }), _react.default.createElement("div", {
    className: "vs-date-picker-calendars"
  }, _react.default.createElement(DatePickerSidebar, {
    rangeConfig: sidebarConfig,
    onNamedRangeSelect: rangeSelectHandler(selectedRanges),
    selectedSidebarRanges: selectedNamedRanges,
    selectedRanges: selectedRanges,
    onCalendarRangeUpdate: updateCalendarRanges
  }), _react.default.createElement("div", {
    className: "vs-date-pickers"
  }, R.addIndex(R.zipWith)(function (range, className, idx) {
    return _react.default.createElement(_reactDateRange.DateRange, {
      key: className,
      className: className,
      onChange: function onChange(_ref6) {
        var range = _ref6.range1;
        rangeSelectHandler(updateSelectedRanges(idx, R.props(['startDate', 'endDate'], range), selectedRanges), idx, 'custom');
      },
      moveRangeOnFirstSelection: false,
      ranges: [range],
      minDate: fromInternalDateFormat(minDate).toJSDate(),
      maxDate: fromInternalDateFormat(maxDate).toJSDate(),
      direction: "vertical",
      scroll: {
        enabled: false
      },
      locale: languageToLocale[locale],
      dateDisplayFormat: dateFormat
    });
  }, calendarRangeInput, ['vs-calendar', 'vs-comparison-calendar vs-calendar']))), _react.default.createElement("div", {
    className: "vs-button-bar"
  }, _react.default.createElement(_Button.Button, {
    type: "text",
    onClick: function onClick() {
      onCancel.apply(void 0, arguments);
    },
    className: "vs-cancel-button"
  }, cancelButtonText), _react.default.createElement(_Button.Button, {
    type: "solid-primary",
    onClick: function onClick(_) {
      return onApply(R.map(R.prop('range1'), calendarRangeInput));
    },
    className: "vs-apply-button"
  }, applyButtonText)));
};

exports.DatePicker = DatePicker;
DatePicker.propTypes = {
  selectedRanges: _propTypes.default.array,
  selectedNamedRanges: _propTypes.default.arrayOf(_propTypes.default.string),
  sidebarConfig: _propTypes.default.arrayOf(rangeConfigShape),
  selectableRange: _propTypes.default.array,
  updateCalendarRanges: _propTypes.default.func.isRequired,
  updateNamedCalendarRanges: _propTypes.default.func.isRequired,
  onApply: _propTypes.default.func.isRequired,
  cancelButtonText: _propTypes.default.node,
  applyButtonText: _propTypes.default.node
};

var _default = (0, _ErrorBoundary.withErrorBoundary)(DatePicker);
/*
 * Usage: sidebarSection(
 *     sectionRange('id', 'Label', ["2018-01-01", "2018-02-02"]),
 *     sectionTitle('Title'),
 * )
 */


exports.default = _default;

var sidebarSection = function sidebarSection(title) {
  for (var _len = arguments.length, ranges = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    ranges[_key - 1] = arguments[_key];
  }

  return R.pipe.apply(R, [title].concat(ranges))({});
};

exports.sidebarSection = sidebarSection;
var sectionTitle = R.assoc('title');
exports.sectionTitle = sectionTitle;
var sectionRange = R.curry(function (id, label, range, section) {
  return R.over(R.lensProp('ranges'), R.append({
    id: id,
    label: label,
    range: range
  }), section);
});
exports.sectionRange = sectionRange;