"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.processExport = exports.mapStateToProps = exports.mapDispatchToProps = exports.downloadFile = exports.MetricsExportComponent = exports.MetricsExport = void 0;
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/esm/objectSpread2"));
var _react = _interopRequireWildcard(require("react"));
var _store = require("../../../redux/store");
var _recompose = require("recompose");
var _reactstrap = require("reactstrap");
var _react2 = require("@kineticdata/react");
var _export = require("../../../redux/modules/export");
var _constants = require("../../../constants");
var _moment = _interopRequireDefault(require("moment"));
var _downloadjs = _interopRequireDefault(require("downloadjs"));
var _papaparse = _interopRequireDefault(require("papaparse"));
var MetricsExportComponent = exports.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 = (0, _moment["default"])(selectedDate);
  return date.isValid() ? /*#__PURE__*/_react["default"].createElement("div", {
    className: "row"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "col-12"
  }, /*#__PURE__*/_react["default"].createElement(_reactstrap.Alert, {
    color: "info",
    isOpen: !!exportStatus,
    toggle: !exporting ? function () {
      return setExportStatus(null);
    } : undefined
  }, !error ? /*#__PURE__*/_react["default"].createElement(_react.Fragment, null, exportStatus === 'Exporting' && /*#__PURE__*/_react["default"].createElement(_react.Fragment, null, /*#__PURE__*/_react["default"].createElement("span", {
    className: "fa fa-spinner fa-spin fa-fw"
  }), /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, exportMessage)), exportStatus === 'Empty' && /*#__PURE__*/_react["default"].createElement(_react.Fragment, null, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "No records found for the selected date range.")), exportStatus === 'Completed' && /*#__PURE__*/_react["default"].createElement(_react.Fragment, null, /*#__PURE__*/_react["default"].createElement(_react2.I18n, {
    render: function render(translate) {
      return translate('Exported # record(s) to').replace('#', data.size);
    }
  }), ' ', /*#__PURE__*/_react["default"].createElement("strong", null, filename))) : /*#__PURE__*/_react["default"].createElement(_react.Fragment, null, /*#__PURE__*/_react["default"].createElement("span", {
    className: "fa fa-exclamation-triangle fa-fw"
  }), /*#__PURE__*/_react["default"].createElement(_react2.I18n, {
    render: function render(translate) {
      return "".concat(translate('Export failed:'), " ").concat(error.message);
    }
  })))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "col-lg-6 mb-5"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "section__title export-title"
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Appointments"), /*#__PURE__*/_react["default"].createElement(_react2.I18n, {
    render: function render(translate) {
      return /*#__PURE__*/_react["default"].createElement("small", null, "".concat(translate('for'), " ").concat(translate(scheduler ? scheduler.values['Name'] : 'All Tech Bars')).concat(scheduler && eventType ? ": ".concat(translate(eventType)) : ''));
    }
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: "export-buttons"
  }, /*#__PURE__*/_react["default"].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(_constants.APPOINTMENT_FORM_SLUG, false);
    }
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Export for"), ' ', /*#__PURE__*/_react["default"].createElement(_react2.Moment, {
    timestamp: date,
    format: "dddd, LL"
  })), /*#__PURE__*/_react["default"].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(_constants.APPOINTMENT_FORM_SLUG, true);
    }
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Export for"), ' ', /*#__PURE__*/_react["default"].createElement(_react2.Moment, {
    timestamp: date,
    format: "MMMM YYYY"
  })))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "col-lg-6 mb-5"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "section__title export-title"
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Walk-Ins"), /*#__PURE__*/_react["default"].createElement(_react2.I18n, {
    render: function render(translate) {
      return /*#__PURE__*/_react["default"].createElement("small", null, "".concat(translate('for'), " ").concat(translate(scheduler ? scheduler.values['Name'] : 'All Tech Bars')).concat(scheduler && eventType ? ": ".concat(translate(eventType)) : ''));
    }
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: "export-buttons"
  }, /*#__PURE__*/_react["default"].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(_constants.WALK_IN_FORM_SLUG, false);
    }
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Export for"), ' ', /*#__PURE__*/_react["default"].createElement(_react2.Moment, {
    timestamp: date,
    format: "dddd, LL"
  })), /*#__PURE__*/_react["default"].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(_constants.WALK_IN_FORM_SLUG, true);
    }
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Export for"), ' ', /*#__PURE__*/_react["default"].createElement(_react2.Moment, {
    timestamp: date,
    format: "MMMM YYYY"
  })))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "col-lg-6 mb-5"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "section__title export-title"
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Appointment Feedback"), /*#__PURE__*/_react["default"].createElement(_react2.I18n, {
    render: function render(translate) {
      return /*#__PURE__*/_react["default"].createElement("small", null, "".concat(translate('for'), " ").concat(translate(scheduler ? scheduler.values['Name'] : 'All Tech Bars')));
    }
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: "export-buttons"
  }, /*#__PURE__*/_react["default"].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(_constants.FEEDBACK_FORM_SLUG, false);
    }
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Export for"), ' ', /*#__PURE__*/_react["default"].createElement(_react2.Moment, {
    timestamp: date,
    format: "dddd, LL"
  })), /*#__PURE__*/_react["default"].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(_constants.FEEDBACK_FORM_SLUG, true);
    }
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Export for"), ' ', /*#__PURE__*/_react["default"].createElement(_react2.Moment, {
    timestamp: date,
    format: "MMMM YYYY"
  })))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "col-lg-6 mb-5"
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "section__title export-title"
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "General Feedback"), /*#__PURE__*/_react["default"].createElement(_react2.I18n, {
    render: function render(translate) {
      return /*#__PURE__*/_react["default"].createElement("small", null, "".concat(translate('for'), " ").concat(translate(scheduler ? scheduler.values['Name'] : 'All Tech Bars')));
    }
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: "export-buttons"
  }, /*#__PURE__*/_react["default"].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(_constants.GENERAL_FEEDBACK_FORM_SLUG, false);
    }
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Export for"), ' ', /*#__PURE__*/_react["default"].createElement(_react2.Moment, {
    timestamp: date,
    format: "dddd, LL"
  })), /*#__PURE__*/_react["default"].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(_constants.GENERAL_FEEDBACK_FORM_SLUG, true);
    }
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Export for"), ' ', /*#__PURE__*/_react["default"].createElement(_react2.Moment, {
    timestamp: date,
    format: "MMMM YYYY"
  }))))) : /*#__PURE__*/_react["default"].createElement("div", {
    className: "alert alert-danger"
  }, /*#__PURE__*/_react["default"].createElement(_react2.I18n, null, "Please select a valid date to see export options."));
};
var processExport = exports.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 = (0, _moment["default"])(selectedDate);
    var schedulerIds = schedulerId ? [schedulerId] : techBars.toJS().map(function (techBar) {
      return techBar.values['Id'];
    });
    switch (formSlug) {
      case _constants.APPOINTMENT_FORM_SLUG:
      case _constants.WALK_IN_FORM_SLUG:
        var isAppointment = formSlug === _constants.APPOINTMENT_FORM_SLUG;
        var dates = month ? Array(date.daysInMonth()).fill().map(function (v, i) {
          return date.clone().startOf('month').add(i, 'day').format(_constants.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 _constants.FEEDBACK_FORM_SLUG:
      case _constants.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:
    }
  };
};
var downloadFile = exports.downloadFile = function downloadFile(_ref3) {
  var data = _ref3.data,
    filename = _ref3.filename,
    setExportStatus = _ref3.setExportStatus;
  return function () {
    var csv = _papaparse["default"].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((0, _objectSpread2["default"])({
        'Property: id': submission.id,
        'Property: createdAt': submission.createdAt,
        'Property: createdBy': submission.createdBy,
        'Property: closedAt': submission.closedAt,
        'Property: closedBy': submission.closedBy
      }, submissionValues));
      return csv;
    }, []));
    (0, _downloadjs["default"])(csv, filename, 'text/csv');
    setExportStatus('Completed');
  };
};
var mapStateToProps = exports.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
  };
};
var mapDispatchToProps = exports.mapDispatchToProps = {
  fetchExportSubmissionsRequest: _export.actions.fetchExportSubmissionsRequest
};
var MetricsExport = exports.MetricsExport = (0, _recompose.compose)((0, _store.connect)(mapStateToProps, mapDispatchToProps), (0, _recompose.withState)('exportStatus', 'setExportStatus', null),
// Exporting, Empty, Completed
(0, _recompose.withState)('exportMessage', 'setExportMessage', null), (0, _recompose.withState)('filename', 'setFilename', ''), (0, _recompose.withHandlers)({
  processExport: processExport,
  downloadFile: downloadFile
}), (0, _recompose.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);