import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import React, { Fragment } from 'react';
import { connect } from '../../../redux/store';
import { compose, lifecycle, withHandlers, withState } from 'recompose';
import { Alert } from 'reactstrap';
import { I18n, Moment } from '@kineticdata/react';
import { actions } from '../../../redux/modules/export';
import { APPOINTMENT_FORM_SLUG, DATE_FORMAT, FEEDBACK_FORM_SLUG, GENERAL_FEEDBACK_FORM_SLUG, WALK_IN_FORM_SLUG } from '../../../constants';
import moment from 'moment';
import downloadjs from 'downloadjs';
import papaparse from 'papaparse';
export var MetricsExportComponent = function MetricsExportComponent(_ref) {
  var selectedDate = _ref.selectedDate,
      scheduler = _ref.scheduler,
      eventType = _ref.eventType,
      exporting = _ref.exporting,
      data = _ref.data,
      error = _ref.error,
      exportStatus = _ref.exportStatus,
      setExportStatus = _ref.setExportStatus,
      exportMessage = _ref.exportMessage,
      setExportMessage = _ref.setExportMessage,
      filename = _ref.filename,
      setFilename = _ref.setFilename,
      processExport = _ref.processExport;
  var date = moment(selectedDate);
  return date.isValid() ? /*#__PURE__*/React.createElement("div", {
    className: "row"
  }, /*#__PURE__*/React.createElement("div", {
    className: "col-12"
  }, /*#__PURE__*/React.createElement(Alert, {
    color: "info",
    isOpen: !!exportStatus,
    toggle: !exporting ? function () {
      return setExportStatus(null);
    } : undefined
  }, !error ? /*#__PURE__*/React.createElement(Fragment, null, exportStatus === 'Exporting' && /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement("span", {
    className: "fa fa-spinner fa-spin fa-fw"
  }), /*#__PURE__*/React.createElement(I18n, null, exportMessage)), exportStatus === 'Empty' && /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(I18n, null, "No records found for the selected date range.")), exportStatus === 'Completed' && /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(I18n, {
    render: function render(translate) {
      return translate('Exported # record(s) to').replace('#', data.size);
    }
  }), ' ', /*#__PURE__*/React.createElement("strong", null, filename))) : /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement("span", {
    className: "fa fa-exclamation-triangle fa-fw"
  }), /*#__PURE__*/React.createElement(I18n, {
    render: function render(translate) {
      return "".concat(translate('Export failed:'), " ").concat(error.message);
    }
  })))), /*#__PURE__*/React.createElement("div", {
    className: "col-lg-6 mb-5"
  }, /*#__PURE__*/React.createElement("div", {
    className: "section__title export-title"
  }, /*#__PURE__*/React.createElement(I18n, null, "Appointments"), /*#__PURE__*/React.createElement(I18n, {
    render: function render(translate) {
      return /*#__PURE__*/React.createElement("small", null, "".concat(translate('for'), " ").concat(translate(scheduler ? scheduler.values['Name'] : 'All Tech Bars')).concat(scheduler && eventType ? ": ".concat(translate(eventType)) : ''));
    }
  })), /*#__PURE__*/React.createElement("div", {
    className: "export-buttons"
  }, /*#__PURE__*/React.createElement("button", {
    className: "btn btn-primary",
    disabled: exporting,
    onClick: function onClick() {
      setExportMessage('Exporting Appointment Records');
      setFilename("".concat([date.format('YYYY-MM-DD'), 'Appointments', scheduler ? scheduler.values['Name'] : 'All Tech Bars', scheduler && eventType ? eventType : undefined].filter(function (a) {
        return a;
      }).join(' - '), ".csv"));
      processExport(APPOINTMENT_FORM_SLUG, false);
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Export for"), ' ', /*#__PURE__*/React.createElement(Moment, {
    timestamp: date,
    format: "dddd, LL"
  })), /*#__PURE__*/React.createElement("button", {
    className: "btn btn-primary",
    disabled: exporting,
    onClick: function onClick() {
      setExportMessage('Exporting Appointment Records');
      setFilename("".concat([date.format('YYYY-MM'), 'Appointments', scheduler ? scheduler.values['Name'] : 'All Tech Bars', scheduler && eventType ? eventType : undefined].filter(function (a) {
        return a;
      }).join(' - '), ".csv"));
      processExport(APPOINTMENT_FORM_SLUG, true);
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Export for"), ' ', /*#__PURE__*/React.createElement(Moment, {
    timestamp: date,
    format: "MMMM YYYY"
  })))), /*#__PURE__*/React.createElement("div", {
    className: "col-lg-6 mb-5"
  }, /*#__PURE__*/React.createElement("div", {
    className: "section__title export-title"
  }, /*#__PURE__*/React.createElement(I18n, null, "Walk-Ins"), /*#__PURE__*/React.createElement(I18n, {
    render: function render(translate) {
      return /*#__PURE__*/React.createElement("small", null, "".concat(translate('for'), " ").concat(translate(scheduler ? scheduler.values['Name'] : 'All Tech Bars')).concat(scheduler && eventType ? ": ".concat(translate(eventType)) : ''));
    }
  })), /*#__PURE__*/React.createElement("div", {
    className: "export-buttons"
  }, /*#__PURE__*/React.createElement("button", {
    className: "btn btn-primary",
    disabled: exporting,
    onClick: function onClick() {
      setExportMessage('Exporting Walk-In Records');
      setFilename("".concat([date.format('YYYY-MM-DD'), 'Walk-Ins', scheduler ? scheduler.values['Name'] : 'All Tech Bars', scheduler && eventType ? eventType : undefined].filter(function (a) {
        return a;
      }).join(' - '), ".csv"));
      processExport(WALK_IN_FORM_SLUG, false);
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Export for"), ' ', /*#__PURE__*/React.createElement(Moment, {
    timestamp: date,
    format: "dddd, LL"
  })), /*#__PURE__*/React.createElement("button", {
    className: "btn btn-primary",
    disabled: exporting,
    onClick: function onClick() {
      setExportMessage('Exporting Walk-In Records');
      setFilename("".concat([date.format('YYYY-MM'), 'Walk-Ins', scheduler ? scheduler.values['Name'] : 'All Tech Bars', scheduler && eventType ? eventType : undefined].filter(function (a) {
        return a;
      }).join(' - '), ".csv"));
      processExport(WALK_IN_FORM_SLUG, true);
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Export for"), ' ', /*#__PURE__*/React.createElement(Moment, {
    timestamp: date,
    format: "MMMM YYYY"
  })))), /*#__PURE__*/React.createElement("div", {
    className: "col-lg-6 mb-5"
  }, /*#__PURE__*/React.createElement("div", {
    className: "section__title export-title"
  }, /*#__PURE__*/React.createElement(I18n, null, "Appointment Feedback"), /*#__PURE__*/React.createElement(I18n, {
    render: function render(translate) {
      return /*#__PURE__*/React.createElement("small", null, "".concat(translate('for'), " ").concat(translate(scheduler ? scheduler.values['Name'] : 'All Tech Bars')));
    }
  })), /*#__PURE__*/React.createElement("div", {
    className: "export-buttons"
  }, /*#__PURE__*/React.createElement("button", {
    className: "btn btn-primary",
    disabled: exporting,
    onClick: function onClick() {
      setExportMessage('Exporting Appointment Feedback Records');
      setFilename("".concat([date.format('YYYY-MM-DD'), 'Appointment Feedback', scheduler ? scheduler.values['Name'] : 'All Tech Bars'].join(' - '), ".csv"));
      processExport(FEEDBACK_FORM_SLUG, false);
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Export for"), ' ', /*#__PURE__*/React.createElement(Moment, {
    timestamp: date,
    format: "dddd, LL"
  })), /*#__PURE__*/React.createElement("button", {
    className: "btn btn-primary",
    disabled: exporting,
    onClick: function onClick() {
      setExportMessage('Exporting Appointment Feedback Records');
      setFilename("".concat([date.format('YYYY-MM'), 'Appointment Feedback', scheduler ? scheduler.values['Name'] : 'All Tech Bars'].join(' - '), ".csv"));
      processExport(FEEDBACK_FORM_SLUG, true);
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Export for"), ' ', /*#__PURE__*/React.createElement(Moment, {
    timestamp: date,
    format: "MMMM YYYY"
  })))), /*#__PURE__*/React.createElement("div", {
    className: "col-lg-6 mb-5"
  }, /*#__PURE__*/React.createElement("div", {
    className: "section__title export-title"
  }, /*#__PURE__*/React.createElement(I18n, null, "General Feedback"), /*#__PURE__*/React.createElement(I18n, {
    render: function render(translate) {
      return /*#__PURE__*/React.createElement("small", null, "".concat(translate('for'), " ").concat(translate(scheduler ? scheduler.values['Name'] : 'All Tech Bars')));
    }
  })), /*#__PURE__*/React.createElement("div", {
    className: "export-buttons"
  }, /*#__PURE__*/React.createElement("button", {
    className: "btn btn-primary",
    disabled: exporting,
    onClick: function onClick() {
      setExportMessage('Exporting General Feedback Records');
      setFilename("".concat([date.format('YYYY-MM-DD'), 'General Feedback', scheduler ? scheduler.values['Name'] : 'All Tech Bars'].join(' - '), ".csv"));
      processExport(GENERAL_FEEDBACK_FORM_SLUG, false);
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Export for"), ' ', /*#__PURE__*/React.createElement(Moment, {
    timestamp: date,
    format: "dddd, LL"
  })), /*#__PURE__*/React.createElement("button", {
    className: "btn btn-primary",
    disabled: exporting,
    onClick: function onClick() {
      setExportMessage('Exporting General Feedback Records');
      setFilename("".concat([date.format('YYYY-MM'), 'General Feedback', scheduler ? scheduler.values['Name'] : 'All Tech Bars'].join(' - '), ".csv"));
      processExport(GENERAL_FEEDBACK_FORM_SLUG, true);
    }
  }, /*#__PURE__*/React.createElement(I18n, null, "Export for"), ' ', /*#__PURE__*/React.createElement(Moment, {
    timestamp: date,
    format: "MMMM YYYY"
  }))))) : /*#__PURE__*/React.createElement("div", {
    className: "alert alert-danger"
  }, /*#__PURE__*/React.createElement(I18n, null, "Please select a valid date to see export options."));
};
export var processExport = function processExport(_ref2) {
  var fetchExportSubmissionsRequest = _ref2.fetchExportSubmissionsRequest,
      schedulerId = _ref2.schedulerId,
      eventType = _ref2.eventType,
      selectedDate = _ref2.selectedDate,
      techBars = _ref2.techBars;
  return function (formSlug, month) {
    var date = moment(selectedDate);
    var schedulerIds = schedulerId ? [schedulerId] : techBars.toJS().map(function (techBar) {
      return techBar.values['Id'];
    });

    switch (formSlug) {
      case APPOINTMENT_FORM_SLUG:
      case WALK_IN_FORM_SLUG:
        var isAppointment = formSlug === APPOINTMENT_FORM_SLUG;
        var dates = month ? Array(date.daysInMonth()).fill().map(function (v, i) {
          return date.clone().startOf('month').add(i, 'day').format(DATE_FORMAT);
        }) : [selectedDate];
        fetchExportSubmissionsRequest({
          formSlug: formSlug,
          schedulerIds: schedulerIds,
          eventType: eventType,
          dates: dates,
          dateFieldName: isAppointment ? 'Event Date' : 'Date',
          queryBuilder: function queryBuilder(searcher) {
            searcher.coreState('Closed');
          }
        });
        break;

      case FEEDBACK_FORM_SLUG:
      case GENERAL_FEEDBACK_FORM_SLUG:
        fetchExportSubmissionsRequest({
          formSlug: formSlug,
          schedulerIds: schedulerIds,
          queryBuilder: function queryBuilder(searcher) {
            if (month) {
              searcher.startDate(date.startOf('month').toDate());
              searcher.endDate(date.add(1, 'month').startOf('month').toDate());
            } else {
              searcher.startDate(date.startOf('day').toDate());
              searcher.endDate(date.add(1, 'day').startOf('day').toDate());
            }
          }
        });
        break;

      default:
    }
  };
};
export var downloadFile = function downloadFile(_ref3) {
  var data = _ref3.data,
      filename = _ref3.filename,
      setExportStatus = _ref3.setExportStatus;
  return function () {
    var csv = papaparse.unparse(data.reduce(function (csv, submission) {
      var submissionValues = submission.values;
      submission.form.fields.forEach(function (field) {
        // If older submissions don't have a new field then add it with a value of null.
        if (!submissionValues.hasOwnProperty(field.name)) {
          submissionValues[field.name] = null;
        } // Checkbox Array values must be stringifyed to retain their array brackets.
        else if (Array.isArray(submissionValues[field.name])) {
            submissionValues[field.name] = JSON.stringify(submissionValues[field.name]);
          }
      });
      csv.push(_objectSpread({
        'Property: id': submission.id,
        'Property: createdAt': submission.createdAt,
        'Property: createdBy': submission.createdBy,
        'Property: closedAt': submission.closedAt,
        'Property: closedBy': submission.closedBy
      }, submissionValues));
      return csv;
    }, []));
    downloadjs(csv, filename, 'text/csv');
    setExportStatus('Completed');
  };
};
export var mapStateToProps = function mapStateToProps(state, props) {
  return {
    scheduler: state.techBarApp.schedulers.find(function (scheduler) {
      return scheduler.values['Id'] === props.schedulerId;
    }),
    exporting: state["export"].exporting,
    data: state["export"].data,
    error: state["export"].error
  };
};
export var mapDispatchToProps = {
  fetchExportSubmissionsRequest: actions.fetchExportSubmissionsRequest
};
export var MetricsExport = compose(connect(mapStateToProps, mapDispatchToProps), withState('exportStatus', 'setExportStatus', null), // Exporting, Empty, Completed
withState('exportMessage', 'setExportMessage', null), withState('filename', 'setFilename', ''), withHandlers({
  processExport: processExport,
  downloadFile: downloadFile
}), lifecycle({
  componentDidUpdate: function componentDidUpdate(prevProps) {
    if (!this.props.exporting && prevProps.exporting && !this.props.error) {
      if (this.props.data.size > 0) {
        this.props.downloadFile();
      } else {
        this.props.setExportStatus('Empty');
      }
    } else if (this.props.exporting && !prevProps.exporting) {
      this.props.setExportStatus('Exporting');
    }
  }
}))(MetricsExportComponent);