import React, { Fragment } from 'react';
import { connect } from '../../redux/store';
import { compose, lifecycle, withHandlers, withProps, withState } from 'recompose';
import { Utils, selectHasRoleSchedulerAdmin } from '@kineticdata/bundle-common';
import { PageTitle } from '../shared/PageTitle';
import { isActiveClass } from '../../utils';
import { Link } from '@reach/router';
import { MetricsSummary } from './metrics/MetricsSummary';
import { MetricsTrend } from './metrics/MetricsTrend';
import { MetricsExport } from './metrics/MetricsExport';
import { actions } from '../../redux/modules/metrics';
import { DATE_FORMAT, MONTH_FORMAT } from '../../constants';
import { I18n } from '@kineticdata/react';
import moment from 'moment';
export var 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;
  return /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(PageTitle, {
    parts: ['Metrics'],
    settings: true
  }), /*#__PURE__*/React.createElement("div", {
    className: "page-container"
  }, /*#__PURE__*/React.createElement("div", {
    className: "page-panel page-panel--white page-panel--tech-bar-metrics"
  }, /*#__PURE__*/React.createElement("div", {
    className: "page-title"
  }, /*#__PURE__*/React.createElement("div", {
    role: "navigation",
    "aria-label": "breadcrumbs",
    className: "page-title__breadcrumbs"
  }, /*#__PURE__*/React.createElement("span", {
    className: "breadcrumb-item"
  }, /*#__PURE__*/React.createElement(Link, {
    to: "../../".concat(mode ? '../' : '')
  }, /*#__PURE__*/React.createElement(I18n, null, "tech bar"))), ' ', /*#__PURE__*/React.createElement("span", {
    "aria-hidden": "true"
  }, "/ "), /*#__PURE__*/React.createElement("span", {
    className: "breadcrumb-item"
  }, /*#__PURE__*/React.createElement(Link, {
    to: "../".concat(mode ? '../' : '')
  }, /*#__PURE__*/React.createElement(I18n, null, "settings"))), ' ', /*#__PURE__*/React.createElement("span", {
    "aria-hidden": "true"
  }, "/ "), /*#__PURE__*/React.createElement("h1", null, /*#__PURE__*/React.createElement(I18n, null, "Metrics")))), /*#__PURE__*/React.createElement("div", {
    className: "form p-0"
  }, /*#__PURE__*/React.createElement("div", {
    className: "row"
  }, /*#__PURE__*/React.createElement("div", {
    className: "form-group col-md-6"
  }, /*#__PURE__*/React.createElement("label", {
    htmlFor: "scheduler-select"
  }, /*#__PURE__*/React.createElement(I18n, null, "Tech Bar")), /*#__PURE__*/React.createElement(I18n, {
    render: function render(translate) {
      return /*#__PURE__*/React.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.createElement("option", {
        value: ""
      }, translate('All Tech Bars')), techBars.map(function (techBar) {
        return /*#__PURE__*/React.createElement("option", {
          value: techBar.values['Id'],
          key: techBar.values['Id']
        }, translate(techBar.values['Name']));
      }));
    }
  })), schedulerId && /*#__PURE__*/React.createElement("div", {
    className: "form-group col-md-6"
  }, /*#__PURE__*/React.createElement("label", {
    htmlFor: "event-type-select"
  }, "Event Type"), /*#__PURE__*/React.createElement(I18n, {
    render: function render(translate) {
      return /*#__PURE__*/React.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.createElement("option", {
        value: ""
      }, translate('All Event Types')), eventTypes.map(function (eventType) {
        return /*#__PURE__*/React.createElement("option", {
          value: eventType,
          key: eventType
        }, translate(eventType));
      }));
    }
  })))), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("ul", {
    className: "nav nav-tabs"
  }, /*#__PURE__*/React.createElement("li", {
    role: "presentation",
    className: "nav-item"
  }, /*#__PURE__*/React.createElement(Link, {
    to: "".concat(mode ? '../' : ''),
    getProps: isActiveClass('nav-link'),
    onClick: function onClick() {
      if (selectedRange !== 'last30Days') {
        setSelectedRange('last30Days');
        fetchMetricsReset();
      }
    }
  }, /*#__PURE__*/React.createElement(I18n, null, /*#__PURE__*/React.createElement(I18n, null, "Summary")))), /*#__PURE__*/React.createElement("li", {
    role: "presentation",
    className: "nav-item"
  }, /*#__PURE__*/React.createElement(Link, {
    to: "".concat(mode ? '../' : '', "trend"),
    getProps: isActiveClass('nav-link'),
    onClick: function onClick() {
      if (selectedRange !== 'last12Months') {
        setSelectedRange('last12Months');
        fetchMetricsReset();
      }
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Trend"))), /*#__PURE__*/React.createElement("li", {
    role: "presentation",
    className: "nav-item"
  }, /*#__PURE__*/React.createElement(Link, {
    to: "".concat(mode ? '../' : '', "export"),
    getProps: isActiveClass('nav-link'),
    onClick: function onClick() {
      fetchMetricsReset();
      setSelectedRange('singleDay');
      setSelectedDate(moment().add(-1, 'day').format(DATE_FORMAT));
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Export")))), /*#__PURE__*/React.createElement("div", {
    className: "form p-0 my-3"
  }, tabMode !== 'export' ? /*#__PURE__*/React.createElement("div", {
    className: "row"
  }, /*#__PURE__*/React.createElement("div", {
    className: "form-group col-md-6"
  }, /*#__PURE__*/React.createElement("label", {
    htmlFor: "date-range-select"
  }, /*#__PURE__*/React.createElement(I18n, null, "Date Range")), /*#__PURE__*/React.createElement(I18n, {
    render: function render(translate) {
      return /*#__PURE__*/React.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' ? moment().startOf('month').format(DATE_FORMAT) : moment().add(-1, 'day').format(DATE_FORMAT));
          fetchMetricsReset();
        }
      }, tabMode === 'summary' && /*#__PURE__*/React.createElement("option", {
        value: "singleDay"
      }, translate('Single Day')), /*#__PURE__*/React.createElement("option", {
        value: "last7Days"
      }, translate('Last 7 Days')), /*#__PURE__*/React.createElement("option", {
        value: "last30Days"
      }, translate('Last 30 Days')), /*#__PURE__*/React.createElement("option", {
        value: "singleMonth"
      }, translate('Single Month')), /*#__PURE__*/React.createElement("option", {
        value: "monthToDate"
      }, translate('Month to Date')), tabMode === 'trend' && /*#__PURE__*/React.createElement("option", {
        value: "last12Months"
      }, translate('Last 12 Months')), tabMode === 'trend' && /*#__PURE__*/React.createElement("option", {
        value: "yearToDate"
      }, translate('Year To Date')));
    }
  })), (selectedRange === 'singleDay' || selectedRange === 'singleMonth') && /*#__PURE__*/React.createElement("div", {
    className: "form-group col-md-6"
  }, /*#__PURE__*/React.createElement("label", {
    htmlFor: "date-select"
  }, /*#__PURE__*/React.createElement(I18n, null, "Date")), /*#__PURE__*/React.createElement("input", {
    type: "date",
    id: "date-select",
    className: "form-control",
    value: selectedDate,
    onChange: function onChange(e) {
      var date = moment(e.target.value);
      var newDate = date.isValid() && selectedRange === 'singleMonth' ? moment(e.target.value).startOf('month').format(DATE_FORMAT) : e.target.value;
      setSelectedDate(newDate);

      if (selectedDate !== newDate) {
        fetchMetricsReset();
      }
    }
  }))) : /*#__PURE__*/React.createElement("div", {
    className: "row"
  }, /*#__PURE__*/React.createElement("div", {
    className: "form-group col-md-6"
  }, /*#__PURE__*/React.createElement("label", {
    htmlFor: "date-select"
  }, /*#__PURE__*/React.createElement(I18n, null, "Date")), /*#__PURE__*/React.createElement("input", {
    type: "date",
    id: "date-select",
    className: "form-control",
    value: selectedDate,
    onChange: function onChange(e) {
      setSelectedDate(e.target.value);
    }
  })))), tabMode === 'summary' && /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(MetricsSummary, {
    schedulerId: schedulerId,
    eventType: eventType,
    techBars: techBars
  })), tabMode === 'trend' && /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(MetricsTrend, {
    schedulerId: schedulerId,
    eventType: eventType,
    techBars: techBars,
    dates: dateRanges[selectedRange] ? dateRanges[selectedRange] : selectedRange === 'singleMonth' ? buildDateRangeForSelectedMonth(selectedDate) : [selectedDate],
    formatDate: function formatDate(date) {
      return moment(date).format(selectedRange === 'last12Months' || selectedRange === 'yearToDate' ? 'MMM, YYYY' : 'll');
    }
  })), tabMode === 'export' && /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(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 = moment().startOf('day');
  var thisMonth = moment().startOf('month');
  return {
    last7Days: fillDateArray(today, 7, 'day', DATE_FORMAT),
    last30Days: fillDateArray(today, 30, 'day', DATE_FORMAT),
    monthToDate: fillDateArray(today, today.date(), 'day', DATE_FORMAT, true),
    last12Months: fillDateArray(thisMonth, 12, 'month', MONTH_FORMAT, true),
    yearToDate: fillDateArray(thisMonth, thisMonth.month() + 1, 'month', MONTH_FORMAT, true)
  };
};

var buildDateRangeForSelectedMonth = function buildDateRangeForSelectedMonth(selectedDate) {
  var month = moment(selectedDate).endOf('month');
  return month.isValid() ? fillDateArray(month, month.daysInMonth(), 'day', DATE_FORMAT, true) : [null];
};

export var mapStateToProps = function mapStateToProps(state, props) {
  var techBars = selectHasRoleSchedulerAdmin(state.app.profile) ? state.techBarApp.schedulers : state.techBarApp.schedulers.filter(function (s) {
    return Utils.isMemberOf(state.app.profile, "Role::Scheduler::".concat(s.values['Name'])) || Utils.isMemberOf(state.app.profile, "Scheduler::".concat(s.values['Name']));
  });
  return {
    kapp: state.app.kapp,
    techBars: techBars,
    metrics: state.metrics.data
  };
};
export var mapDispatchToProps = {
  fetchMetricsRequest: actions.fetchMetricsRequest,
  fetchMetricsReset: 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
    });
  };
};

export var TechBarMetrics = compose(connect(mapStateToProps, mapDispatchToProps), 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'
  };
}), withState('schedulerId', 'setSchedulerId', ''), withState('eventType', 'setEventType', ''), withState('dateRanges', 'setDateRanges', buildDateRanges()), withState('selectedRange', 'setSelectedRange', 'last30Days'), withState('selectedDate', 'setSelectedDate', moment().add(-1, 'day').format(DATE_FORMAT)), withHandlers({
  handleFetch: handleFetch
}), withProps(function (_ref4) {
  var schedulerId = _ref4.schedulerId,
      metrics = _ref4.metrics;
  return {
    eventTypes: schedulerId && metrics.size > 0 ? metrics.getIn([0, 'data', 'eventTypes']).map(function (event) {
      return event.type;
    }) : []
  };
}), 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);