"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.mapStateToProps = exports.mapDispatchToProps = exports.TechBarMetricsComponent = exports.TechBarMetrics = void 0;
var _react = _interopRequireDefault(require("react"));
var _store = require("../../redux/store");
var _recompose = require("recompose");
var _bundleCommon = require("@kineticdata/bundle-common");
var _PageTitle = require("../shared/PageTitle");
var _utils = require("../../utils");
var _router = require("@reach/router");
var _MetricsSummary = require("./metrics/MetricsSummary");
var _MetricsTrend = require("./metrics/MetricsTrend");
var _MetricsExport = require("./metrics/MetricsExport");
var _metrics = require("../../redux/modules/metrics");
var _constants = require("../../constants");
var _react2 = require("@kineticdata/react");
var _moment = _interopRequireDefault(require("moment"));
var TechBarMetricsComponent = exports.TechBarMetricsComponent = function TechBarMetricsComponent(_ref) {
  var fetchMetricsReset = _ref.fetchMetricsReset,
    mode = _ref.mode,
    tabMode = _ref.tabMode,
    schedulerId = _ref.schedulerId,
    setSchedulerId = _ref.setSchedulerId,
    eventType = _ref.eventType,
    setEventType = _ref.setEventType,
    techBars = _ref.techBars,
    eventTypes = _ref.eventTypes,
    dateRanges = _ref.dateRanges,
    selectedRange = _ref.selectedRange,
    setSelectedRange = _ref.setSelectedRange,
    selectedDate = _ref.selectedDate,
    setSelectedDate = _ref.setSelectedDate,
    kapp = _ref.kapp;
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "page-container"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "page-panel page-panel--tech-bar-metrics"
  }, /*#__PURE__*/_react["default"].createElement(_PageTitle.PageTitle, {
    parts: ['Metrics'],
    settings: true,
    breadcrumbs: [{
      label: 'Home',
      to: '/'
    }, {
      label: "".concat(kapp.name, " Settings"),
      to: "../".concat(mode ? '..' : '')
    }],
    title: "Metrics"
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "form p-0"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "row"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "form-group col-md-6"
  }, /*#__PURE__*/_react["default"].createElement("label", {
    htmlFor: "scheduler-select"
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Tech Bar")), /*#__PURE__*/_react["default"].createElement(_react2.I18n, {
    render: function render(translate) {
      return /*#__PURE__*/_react["default"].createElement("select", {
        name: "scheduler-select",
        id: "scheduler-select",
        className: "form-control",
        value: schedulerId,
        onChange: function onChange(e) {
          setSchedulerId(e.target.value);
          setEventType('');
          fetchMetricsReset();
        }
      }, /*#__PURE__*/_react["default"].createElement("option", {
        value: ""
      }, translate('All Tech Bars')), techBars.map(function (techBar) {
        return /*#__PURE__*/_react["default"].createElement("option", {
          value: techBar.values['Id'],
          key: techBar.values['Id']
        }, translate(techBar.values['Name']));
      }));
    }
  })), schedulerId && /*#__PURE__*/_react["default"].createElement("div", {
    className: "form-group col-md-6"
  }, /*#__PURE__*/_react["default"].createElement("label", {
    htmlFor: "event-type-select"
  }, "Event Type"), /*#__PURE__*/_react["default"].createElement(_react2.I18n, {
    render: function render(translate) {
      return /*#__PURE__*/_react["default"].createElement("select", {
        name: "event-type-select",
        id: "event-type-select",
        className: "form-control",
        value: eventType,
        onChange: function onChange(e) {
          setEventType(e.target.value);
        }
      }, /*#__PURE__*/_react["default"].createElement("option", {
        value: ""
      }, translate('All Event Types')), eventTypes.map(function (eventType) {
        return /*#__PURE__*/_react["default"].createElement("option", {
          value: eventType,
          key: eventType
        }, translate(eventType));
      }));
    }
  })))), /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("ul", {
    className: "nav nav-tabs"
  }, /*#__PURE__*/_react["default"].createElement("li", {
    role: "presentation",
    className: "nav-item"
  }, /*#__PURE__*/_react["default"].createElement(_router.Link, {
    to: "".concat(mode ? '../' : ''),
    getProps: (0, _utils.isActiveClass)('nav-link'),
    onClick: function onClick() {
      if (selectedRange !== 'last30Days') {
        setSelectedRange('last30Days');
        fetchMetricsReset();
      }
    }
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Summary")))), /*#__PURE__*/_react["default"].createElement("li", {
    role: "presentation",
    className: "nav-item"
  }, /*#__PURE__*/_react["default"].createElement(_router.Link, {
    to: "".concat(mode ? '../' : '', "trend"),
    getProps: (0, _utils.isActiveClass)('nav-link'),
    onClick: function onClick() {
      if (selectedRange !== 'last12Months') {
        setSelectedRange('last12Months');
        fetchMetricsReset();
      }
    }
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Trend"))), /*#__PURE__*/_react["default"].createElement("li", {
    role: "presentation",
    className: "nav-item"
  }, /*#__PURE__*/_react["default"].createElement(_router.Link, {
    to: "".concat(mode ? '../' : '', "export"),
    getProps: (0, _utils.isActiveClass)('nav-link'),
    onClick: function onClick() {
      fetchMetricsReset();
      setSelectedRange('singleDay');
      setSelectedDate((0, _moment["default"])().add(-1, 'day').format(_constants.DATE_FORMAT));
    }
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Export")))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "form p-0 my-3"
  }, tabMode !== 'export' ? /*#__PURE__*/_react["default"].createElement("div", {
    className: "row"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "form-group col-md-6"
  }, /*#__PURE__*/_react["default"].createElement("label", {
    htmlFor: "date-range-select"
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Date Range")), /*#__PURE__*/_react["default"].createElement(_react2.I18n, {
    render: function render(translate) {
      return /*#__PURE__*/_react["default"].createElement("select", {
        name: "date-range-select",
        id: "date-range-select",
        className: "form-control",
        value: selectedRange,
        onChange: function onChange(e) {
          setSelectedRange(e.target.value);
          setSelectedDate(e.target.value === 'singleMonth' ? (0, _moment["default"])().startOf('month').format(_constants.DATE_FORMAT) : (0, _moment["default"])().add(-1, 'day').format(_constants.DATE_FORMAT));
          fetchMetricsReset();
        }
      }, tabMode === 'summary' && /*#__PURE__*/_react["default"].createElement("option", {
        value: "singleDay"
      }, translate('Single Day')), /*#__PURE__*/_react["default"].createElement("option", {
        value: "last7Days"
      }, translate('Last 7 Days')), /*#__PURE__*/_react["default"].createElement("option", {
        value: "last30Days"
      }, translate('Last 30 Days')), /*#__PURE__*/_react["default"].createElement("option", {
        value: "singleMonth"
      }, translate('Single Month')), /*#__PURE__*/_react["default"].createElement("option", {
        value: "monthToDate"
      }, translate('Month to Date')), tabMode === 'trend' && /*#__PURE__*/_react["default"].createElement("option", {
        value: "last12Months"
      }, translate('Last 12 Months')), tabMode === 'trend' && /*#__PURE__*/_react["default"].createElement("option", {
        value: "yearToDate"
      }, translate('Year To Date')));
    }
  })), (selectedRange === 'singleDay' || selectedRange === 'singleMonth') && /*#__PURE__*/_react["default"].createElement("div", {
    className: "form-group col-md-6"
  }, /*#__PURE__*/_react["default"].createElement("label", {
    htmlFor: "date-select"
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Date")), /*#__PURE__*/_react["default"].createElement("input", {
    type: "date",
    id: "date-select",
    className: "form-control",
    value: selectedDate,
    onChange: function onChange(e) {
      var date = (0, _moment["default"])(e.target.value);
      var newDate = date.isValid() && selectedRange === 'singleMonth' ? (0, _moment["default"])(e.target.value).startOf('month').format(_constants.DATE_FORMAT) : e.target.value;
      setSelectedDate(newDate);
      if (selectedDate !== newDate) {
        fetchMetricsReset();
      }
    }
  }))) : /*#__PURE__*/_react["default"].createElement("div", {
    className: "row"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "form-group col-md-6"
  }, /*#__PURE__*/_react["default"].createElement("label", {
    htmlFor: "date-select"
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Date")), /*#__PURE__*/_react["default"].createElement("input", {
    type: "date",
    id: "date-select",
    className: "form-control",
    value: selectedDate,
    onChange: function onChange(e) {
      setSelectedDate(e.target.value);
    }
  })))), tabMode === 'summary' && /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_MetricsSummary.MetricsSummary, {
    schedulerId: schedulerId,
    eventType: eventType,
    techBars: techBars
  })), tabMode === 'trend' && /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_MetricsTrend.MetricsTrend, {
    schedulerId: schedulerId,
    eventType: eventType,
    techBars: techBars,
    dates: dateRanges[selectedRange] ? dateRanges[selectedRange] : selectedRange === 'singleMonth' ? buildDateRangeForSelectedMonth(selectedDate) : [selectedDate],
    formatDate: function formatDate(date) {
      return (0, _moment["default"])(date).format(selectedRange === 'last12Months' || selectedRange === 'yearToDate' ? 'MMM, YYYY' : 'll');
    }
  })), tabMode === 'export' && /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement(_MetricsExport.MetricsExport, {
    selectedDate: selectedDate,
    schedulerId: schedulerId,
    eventType: eventType,
    techBars: techBars
  })))));
};
var fillDateArray = function fillDateArray(start, length, interval, format) {
  var includeCurrent = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  return Array(length).fill().map(function (v, i) {
    return start.clone().add(-(i + (includeCurrent ? 0 : 1)), interval).format(format);
  });
};
var buildDateRanges = function buildDateRanges() {
  var today = (0, _moment["default"])().startOf('day');
  var thisMonth = (0, _moment["default"])().startOf('month');
  return {
    last7Days: fillDateArray(today, 7, 'day', _constants.DATE_FORMAT),
    last30Days: fillDateArray(today, 30, 'day', _constants.DATE_FORMAT),
    monthToDate: fillDateArray(today, today.date(), 'day', _constants.DATE_FORMAT, true),
    last12Months: fillDateArray(thisMonth, 12, 'month', _constants.MONTH_FORMAT, true),
    yearToDate: fillDateArray(thisMonth, thisMonth.month() + 1, 'month', _constants.MONTH_FORMAT, true)
  };
};
var buildDateRangeForSelectedMonth = function buildDateRangeForSelectedMonth(selectedDate) {
  var month = (0, _moment["default"])(selectedDate).endOf('month');
  return month.isValid() ? fillDateArray(month, month.daysInMonth(), 'day', _constants.DATE_FORMAT, true) : [null];
};
var mapStateToProps = exports.mapStateToProps = function mapStateToProps(state, props) {
  var techBars = (0, _bundleCommon.selectHasRoleSchedulerAdmin)(state.app.profile) ? state.techBarApp.schedulers : state.techBarApp.schedulers.filter(function (s) {
    return _bundleCommon.Utils.isMemberOf(state.app.profile, "Role::Scheduler::".concat(s.values['Name'])) || _bundleCommon.Utils.isMemberOf(state.app.profile, "Scheduler::".concat(s.values['Name']));
  });
  return {
    kapp: state.app.kapp,
    techBars: techBars,
    metrics: state.metrics.data
  };
};
var mapDispatchToProps = exports.mapDispatchToProps = {
  fetchMetricsRequest: _metrics.actions.fetchMetricsRequest,
  fetchMetricsReset: _metrics.actions.fetchMetricsReset
};
var handleFetch = function handleFetch(_ref2) {
  var fetchMetricsReset = _ref2.fetchMetricsReset,
    fetchMetricsRequest = _ref2.fetchMetricsRequest,
    schedulerId = _ref2.schedulerId,
    _ref2$techBars = _ref2.techBars,
    techBars = _ref2$techBars === void 0 ? [] : _ref2$techBars,
    dateRanges = _ref2.dateRanges,
    selectedRange = _ref2.selectedRange,
    selectedDate = _ref2.selectedDate;
  return function () {
    fetchMetricsReset();
    var dates = dateRanges[selectedRange] ? dateRanges[selectedRange] : selectedRange === 'singleMonth' ? buildDateRangeForSelectedMonth(selectedDate) : [selectedDate];
    fetchMetricsRequest({
      schedulerIds: schedulerId ? [schedulerId] : techBars.toJS().map(function (techBar) {
        return techBar.values['Id'];
      }),
      monthly: selectedRange === 'last12Months' || selectedRange === 'yearToDate',
      dates: dates
    });
  };
};
var TechBarMetrics = exports.TechBarMetrics = (0, _recompose.compose)((0, _store.connect)(mapStateToProps, mapDispatchToProps), (0, _recompose.withProps)(function (_ref3) {
  var _ref3$mode = _ref3.mode,
    mode = _ref3$mode === void 0 ? 'summary' : _ref3$mode;
  return {
    tabMode: ['summary', 'trend', 'export'].includes(mode) ? mode : 'summary'
  };
}), (0, _recompose.withState)('schedulerId', 'setSchedulerId', ''), (0, _recompose.withState)('eventType', 'setEventType', ''), (0, _recompose.withState)('dateRanges', 'setDateRanges', buildDateRanges()), (0, _recompose.withState)('selectedRange', 'setSelectedRange', 'last30Days'), (0, _recompose.withState)('selectedDate', 'setSelectedDate', (0, _moment["default"])().add(-1, 'day').format(_constants.DATE_FORMAT)), (0, _recompose.withHandlers)({
  handleFetch: handleFetch
}), (0, _recompose.withProps)(function (_ref4) {
  var schedulerId = _ref4.schedulerId,
    metrics = _ref4.metrics;
  return {
    eventTypes: schedulerId && metrics && metrics.size > 0 ? metrics.getIn([0, 'data', 'eventTypes']).map(function (event) {
      return event.type;
    }) : []
  };
}), (0, _recompose.lifecycle)({
  componentDidMount: function componentDidMount() {
    this.props.handleFetch();
  },
  componentDidUpdate: function componentDidUpdate(prevProps) {
    if (this.props.schedulerId !== prevProps.schedulerId || this.props.selectedRange !== prevProps.selectedRange || this.props.selectedDate !== prevProps.selectedDate) {
      this.props.handleFetch();
    }
  }
}))(TechBarMetricsComponent);