import { a1 as v2, a2 as isPast } from "./dateFns.js";
import { D as DataRetrievalStatus } from "./AccountUtils.js";
import { aM as Enum, aN as CommonValidationErrorType, a3 as Dialog, t, a4 as DialogBody, T as Trans, a5 as DialogFooter, f as Button, Q as ButtonType, N as ButtonStyle, aB as Validation, aA as FormGroupError, aC as FormGroup, J as InputGroup, a as Ctx, h as AlertType, E as ErrorHelper, i as CommonError, g as AccPath, F as FeUtils, O as OverrideCSS, aO as Form, j as Alert, L as Loading } from "./index.js";
import { P as Pagination } from "./Pagination.js";
import { w as withPropsGuard } from "./WithPropsGuard.js";
import { c as classNames } from "./reactSlick.js";
import React__default from "react";
import { A as AccountMainSection, b as AccountMainSectionHeader, a as AccountMainSectionBody } from "./AccountMainSection.js";
import { v as validator } from "./validator.js";
import "./reactPlayer.js";
import "react-router-dom";
const ValidateComplexPasswordErrorType = Enum(CommonValidationErrorType.empty, CommonValidationErrorType.invalidFormat);
const validateComplexPassword = (value, { isRequired = true } = {}) => {
  const REGEX = '^(?:(?=.*\\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))(?!.*(.)\\1{2,})[A-Za-z0-9!~<>,;:_=?*+#."&\xA7%\xB0()\\|\\[\\]\\-\\$\\^\\@\\/]{8,32}$';
  if (validator.exports.isEmpty(value)) {
    if (!isRequired) {
      return null;
    }
    return ValidateComplexPasswordErrorType.empty;
  }
  if (!validator.exports.matches(value, REGEX)) {
    return ValidateComplexPasswordErrorType.invalidFormat;
  }
  return null;
};
var CancelConfirmDialog$1 = "";
class CancelConfirmDialog extends React__default.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const { onCancel, onConfirm } = this.props;
    return /* @__PURE__ */ React__default.createElement(Dialog, {
      className: "cancelConfirmDialog",
      title: t("PersonalDataPage.cancelConfirmDialog.title"),
      isOpen: true
    }, /* @__PURE__ */ React__default.createElement(DialogBody, {
      className: "dialogBody"
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.cancelConfirmDialog.bodyText"
    }, "Do you want to cancel your personal data request?")), /* @__PURE__ */ React__default.createElement(DialogFooter, {
      className: "dialogFooter"
    }, /* @__PURE__ */ React__default.createElement("div", {
      className: "btnContainer"
    }, /* @__PURE__ */ React__default.createElement(Button, {
      className: "btn big btn-ghost btnCancel",
      buttonType: ButtonType.TEXT,
      buttonStyle: ButtonStyle.NONE,
      onClick: () => {
        if (onCancel)
          onCancel();
      }
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.cancelDialogConfirm.close"
    }, "Close")), /* @__PURE__ */ React__default.createElement(Button, {
      className: "btn big btn-primary btnContinue",
      onClick: () => {
        if (onConfirm) {
          onConfirm();
        }
      }
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.cancelDialogConfirm.continue"
    }, "Continue")))));
  }
}
class DownloadConfirmDialog extends React__default.Component {
  constructor(props) {
    super(props);
    this.onPasswordChange = (event) => {
      const password = event.target.value;
      this.validation.set("password", validateComplexPassword(password));
      this.setState({ password });
    };
    this.state = {
      password: ""
    };
    this.validation = new Validation();
    this.validation.listen(() => this.setState({}));
  }
  renderErrorType(errorType) {
    if (errorType === ValidateComplexPasswordErrorType.empty) {
      return /* @__PURE__ */ React__default.createElement(FormGroupError, null, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "PersonalDataPage.inputPasswordForm.inputPasswordError.empty"
      }, "Input your password to proceed"));
    }
    return null;
  }
  render() {
    const { password } = this.state;
    const { onCancel, onConfirm, dateRequest } = this.props;
    return /* @__PURE__ */ React__default.createElement(Dialog, {
      className: "cancelConfirmDialog",
      title: t("PersonalDataPage.downloadConfirmDialog.title"),
      isOpen: true
    }, /* @__PURE__ */ React__default.createElement(DialogBody, {
      className: "dialogBody"
    }, /* @__PURE__ */ React__default.createElement("div", {
      className: "bodyText"
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.downloadConfirmDialog.bodyText"
    }, "Input your password to download")), /* @__PURE__ */ React__default.createElement("form", {
      className: "form",
      onSubmit: (event) => {
        event.preventDefault();
      }
    }, /* @__PURE__ */ React__default.createElement(FormGroup, null, /* @__PURE__ */ React__default.createElement(InputGroup, {
      className: "inputRedeem",
      type: "password",
      value: password,
      placeholder: t("PersonalDataPage.form.passwordPlaceholder"),
      onChange: this.onPasswordChange
    }), this.renderErrorType(this.validation.get("password"))))), /* @__PURE__ */ React__default.createElement(DialogFooter, {
      className: "dialogFooter"
    }, /* @__PURE__ */ React__default.createElement("div", {
      className: "btnContainer"
    }, /* @__PURE__ */ React__default.createElement(Button, {
      className: "btn btn-ghost big btnCancel",
      buttonType: ButtonType.TEXT,
      buttonStyle: ButtonStyle.NONE,
      onClick: () => {
        if (onCancel)
          onCancel();
      }
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.downloadConfirmDialog.cancel"
    }, "Cancel")), /* @__PURE__ */ React__default.createElement(Button, {
      className: "btn btn-primary big btnDownload",
      onClick: () => {
        if (onConfirm) {
          onConfirm(dateRequest, password);
        }
      }
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.cancelDialogConfirm.download"
    }, "Download")))));
  }
}
var PersonalData = "";
var CircleIconStatus$1 = "";
const CircleIconStatus = ({ className }) => /* @__PURE__ */ React__default.createElement("i", {
  className: classNames("circleStatusIcon", className)
}, /* @__PURE__ */ React__default.createElement("svg", {
  className: "fill-current",
  width: "8",
  height: "8",
  viewBox: "0 0 8 8",
  fill: "none",
  xmlns: "http://www.w3.org/2000/svg"
}, /* @__PURE__ */ React__default.createElement("circle", {
  cx: "4",
  cy: "4",
  r: "4"
})));
function requestStatusIcon(status) {
  switch (status) {
    case DataRetrievalStatus.enum.Completed:
      return /* @__PURE__ */ React__default.createElement(CircleIconStatus, {
        className: "completed"
      });
    case DataRetrievalStatus.enum.Pending:
      return /* @__PURE__ */ React__default.createElement(CircleIconStatus, {
        className: "pending"
      });
    case DataRetrievalStatus.enum.Failed:
      return /* @__PURE__ */ React__default.createElement(CircleIconStatus, {
        className: "failed"
      });
    case DataRetrievalStatus.enum.InProgress:
      return /* @__PURE__ */ React__default.createElement(CircleIconStatus, {
        className: "inProgress"
      });
    case DataRetrievalStatus.enum.Expired:
      return /* @__PURE__ */ React__default.createElement(CircleIconStatus, {
        className: "failed"
      });
    default:
      return /* @__PURE__ */ React__default.createElement(CircleIconStatus, {
        className: "pending"
      });
  }
}
class PersonalDataPage extends React__default.Component {
  constructor(props) {
    super(props);
    this.fetchGdprRequestDataList = () => {
      var _a;
      const userId = (_a = Ctx.getAppState().getUser()) == null ? void 0 : _a.userId;
      if (userId) {
        this.logic.fetchGdprRequestDataList(userId, this.getOffset(this.props.page), this.getLimit()).catch((error) => {
          this.setErrorAlert(error);
        });
      }
    };
    this.notifyRequestSuccess = () => {
      this.setState({
        alert: {
          type: AlertType.success,
          element: /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "PersonalDataPage.successRequest"
          }, "Request sent! Please check the status of your request below.")
        }
      });
    };
    this.notifyRequestCancellation = () => {
      this.setState({
        alert: {
          type: AlertType.success,
          element: /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "PersonalDataPage.successCancel"
          }, "Your personal data request has been canceled")
        }
      });
    };
    this.onRequestGdprDataError = (error) => {
      const errorCode = ErrorHelper.extractServiceErrorCode(error);
      if (errorCode) {
        this.setErrorAlert(error);
      } else {
        this.setState({
          alert: {
            type: AlertType.danger,
            element: /* @__PURE__ */ React__default.createElement(Trans, {
              i18nKey: "PersonalDataPage.errorRequest"
            }, "Unable to send the request. Please try again.")
          }
        });
      }
    };
    this.setErrorAlert = (error) => {
      this.setState({
        alert: {
          type: AlertType.danger,
          element: /* @__PURE__ */ React__default.createElement(CommonError, {
            error
          })
        }
      });
    };
    this.clearNotification = () => this.setState({ alert: null });
    this.onPasswordChange = (event) => {
      const password = event.target.value;
      this.validation.set("password", validateComplexPassword(password));
      this.setState({ password });
    };
    this.renderPagination = () => {
      const { gdprDataRequestList } = this.logic.state;
      if (!gdprDataRequestList)
        return;
      const { Paging } = gdprDataRequestList;
      const hasNext = !!Paging.Next;
      const hasPrev = !!Paging.Previous;
      const currentPage = this.props.page;
      return /* @__PURE__ */ React__default.createElement("div", {
        className: "pagination"
      }, /* @__PURE__ */ React__default.createElement(Pagination, {
        next: hasNext && `${AccPath.PersonalData.link}?page=${currentPage + 1}`,
        prev: hasPrev && `${AccPath.PersonalData.link}?page=${currentPage - 1}`
      }));
    };
    this.onSubmit = (event) => {
      var _a;
      event.preventDefault();
      this.setState({ password: "" });
      const userId = (_a = Ctx.getAppState().getUser()) == null ? void 0 : _a.userId;
      if (userId) {
        this.logic.requestGdprData(this.state.password, userId).then(() => {
          this.notifyRequestSuccess();
          this.fetchGdprRequestDataList();
        }).catch((error) => {
          this.setErrorAlert(error);
        });
      }
    };
    this.cancelRequest = (selectedRequestDate) => {
      var _a;
      const userId = (_a = Ctx.getAppState().getUser()) == null ? void 0 : _a.userId;
      if (selectedRequestDate && userId) {
        this.logic.cancelRequestGdprData(selectedRequestDate, userId).then(() => {
          this.notifyRequestCancellation();
        }).catch((error) => {
          this.setErrorAlert(error);
        }).finally(() => {
          this.fetchGdprRequestDataList();
          this.setState({ openCancelDialog: false });
        });
      }
    };
    this.downloadGdpr = (selectedRequestDate, password) => {
      var _a;
      const userId = (_a = Ctx.getAppState().getUser()) == null ? void 0 : _a.userId;
      if (!selectedRequestDate || !password || !userId)
        return;
      this.logic.downloadGdprData(selectedRequestDate, password, userId).then((result) => {
        if (result) {
          window.open(result.URL, "_blank");
        }
      }).catch((error) => {
        this.setErrorAlert(error);
      }).finally(() => {
        this.setState({ openDownloadDialog: false });
      });
    };
    const logic = Ctx.getAppState().gdprAppManager;
    logic.subscribe(() => this.setState({}));
    this.logic = logic;
    this.state = {
      password: "",
      selectedRequestDate: null,
      openCancelDialog: false,
      openDownloadDialog: false,
      alert: null
    };
    this.validation = new Validation();
    this.validation.listen(() => this.setState({}));
  }
  componentDidMount() {
    this.fetchGdprRequestDataList();
  }
  formatSelectedDate(selectedDate) {
    const date = new Date(selectedDate);
    return `${date.toISOString().substring(0, 19)}Z`;
  }
  getLimit() {
    const pageSize = 10;
    return pageSize;
  }
  getOffset(page) {
    return page ? (page - 1) * this.getLimit() : 0;
  }
  renderDownloadAction(isDataRequestComplete, isFileExpired, requestDate) {
    return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, isDataRequestComplete && !isFileExpired && /* @__PURE__ */ React__default.createElement("div", {
      className: "btnDownload",
      onClick: () => this.setState({
        openDownloadDialog: true,
        selectedRequestDate: this.formatSelectedDate(requestDate)
      })
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.action.download"
    }, "Download")));
  }
  renderCancelAction(isDataRequestComplete, isDataRequestFailed, isDataRequestCanceled, requestDate) {
    return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, !isDataRequestComplete && !isDataRequestFailed && !isDataRequestCanceled ? /* @__PURE__ */ React__default.createElement("div", {
      className: "btnCancel",
      onClick: () => this.setState({
        openCancelDialog: true,
        selectedRequestDate: this.formatSelectedDate(requestDate)
      })
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.action.cancel"
    }, "Cancel")) : /* @__PURE__ */ React__default.createElement("span", {
      className: "btnCancel disabled"
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.action.cancel"
    }, "Cancel")));
  }
  renderExpirationDate(isFileExpired, expirationDate, isDataRequestComplete) {
    if (!isDataRequestComplete)
      return "-";
    if (isFileExpired) {
      return /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "PersonalDataPage.fileExpired"
      }, "file expired");
    }
    return FeUtils.formatDate(v2.legacyParse(expirationDate), "LLLL");
  }
  renderListDataRequest(dataRequest) {
    const isDataRequestComplete = dataRequest.Status === DataRetrievalStatus.enum.Completed;
    const isDataRequestFailed = dataRequest.Status === DataRetrievalStatus.enum.Failed;
    const isDataRequestCanceled = dataRequest.Status === DataRetrievalStatus.enum.Canceled;
    const isFileExpired = isPast(v2.legacyParse(dataRequest.DataExpirationDate));
    const dataRequestParseResult = DataRetrievalStatus.safeParse(dataRequest.Status);
    return /* @__PURE__ */ React__default.createElement("tr", {
      key: dataRequest.RequestDate,
      className: "tableRow"
    }, /* @__PURE__ */ React__default.createElement("td", {
      className: "date"
    }, FeUtils.formatDate(v2.legacyParse(dataRequest.RequestDate), "LL")), /* @__PURE__ */ React__default.createElement("td", {
      className: "statusContainer"
    }, /* @__PURE__ */ React__default.createElement("span", {
      className: "statusIcon"
    }, dataRequestParseResult.success && requestStatusIcon(dataRequestParseResult.data)), dataRequest.Status), /* @__PURE__ */ React__default.createElement("td", null, this.renderExpirationDate(isFileExpired, dataRequest.DataExpirationDate, isDataRequestComplete)), /* @__PURE__ */ React__default.createElement("td", null, this.renderDownloadAction(isDataRequestComplete, isFileExpired, dataRequest.RequestDate)), /* @__PURE__ */ React__default.createElement("td", null, this.renderCancelAction(isDataRequestComplete, isDataRequestFailed, isDataRequestCanceled, dataRequest.RequestDate)));
  }
  renderErrorType(errorType) {
    if (errorType === ValidateComplexPasswordErrorType.empty) {
      return /* @__PURE__ */ React__default.createElement(FormGroupError, null, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "PersonalDataPage.inputPasswordForm.inputPasswordError.empty"
      }, "Input your password to proceed"));
    }
    return null;
  }
  render() {
    const { gdprDataRequestList, isRequestingGdpr, isFetchingGdpr } = this.logic.state;
    const { password, openCancelDialog, openDownloadDialog, selectedRequestDate, alert } = this.state;
    const dataRequestLength = gdprDataRequestList ? gdprDataRequestList.Data.length : 0;
    const isDisabledSubmitBtn = !this.validation.isAllValid() || !password || isRequestingGdpr;
    return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement(AccountMainSection, null, /* @__PURE__ */ React__default.createElement(AccountMainSectionHeader, null, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.title"
    }, "Personal Data Request")), /* @__PURE__ */ React__default.createElement(AccountMainSectionBody, null, /* @__PURE__ */ React__default.createElement("div", {
      className: "personalDataPage"
    }, /* @__PURE__ */ React__default.createElement("section", {
      className: "formSection"
    }, /* @__PURE__ */ React__default.createElement("div", {
      className: classNames("guideHeading", OverrideCSS.TITLE_FONT)
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.guideHeading"
    }, "Download Personal Data")), /* @__PURE__ */ React__default.createElement("div", {
      className: "guideText"
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.guide"
    }, "Collecting your data may take up to 28 days. Once your data has been collected, you will have a limited amount of time to download the data.")), /* @__PURE__ */ React__default.createElement("h3", {
      className: "formTextTitle"
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.inputPasswordTitle"
    }, "Input your password to proceed")), /* @__PURE__ */ React__default.createElement(Form, {
      onSubmit: this.onSubmit,
      className: "form",
      orientation: "horizontal"
    }, /* @__PURE__ */ React__default.createElement(FormGroup, null, /* @__PURE__ */ React__default.createElement(InputGroup, {
      className: "inputRedeem",
      type: "password",
      value: password,
      placeholder: t("PersonalDataPage.form.passwordPlaceholder"),
      onChange: this.onPasswordChange
    }), this.renderErrorType(this.validation.get("password"))), /* @__PURE__ */ React__default.createElement(Button, {
      disabled: isDisabledSubmitBtn,
      className: "btn btn-primary buttonSendRequest",
      type: "submit"
    }, isRequestingGdpr ? /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.processing"
    }, "Processing...") : /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.buttonAction"
    }, "Send Request"))), !!alert && /* @__PURE__ */ React__default.createElement(Alert, {
      type: alert.type,
      className: "alertContainer",
      onDismiss: this.clearNotification
    }, alert.element)), /* @__PURE__ */ React__default.createElement("section", {
      className: "fileSection"
    }, isFetchingGdpr && /* @__PURE__ */ React__default.createElement("div", {
      className: "loadingContainer"
    }, /* @__PURE__ */ React__default.createElement(Loading, {
      className: "loading"
    })), !isFetchingGdpr && gdprDataRequestList && /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement("h1", {
      className: "title"
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.filesTitle"
    }, "Files"), " (", dataRequestLength, ")"), dataRequestLength > 0 ? /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement("table", null, /* @__PURE__ */ React__default.createElement("thead", null, /* @__PURE__ */ React__default.createElement("tr", null, /* @__PURE__ */ React__default.createElement("th", null, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.table.date"
    }, "Date")), /* @__PURE__ */ React__default.createElement("th", null, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.table.status"
    }, "Status")), /* @__PURE__ */ React__default.createElement("th", null, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.table.fileExpiration"
    }, "File expiration")), /* @__PURE__ */ React__default.createElement("th", {
      colSpan: 2
    }, "\xA0"), /* @__PURE__ */ React__default.createElement("th", null))), /* @__PURE__ */ React__default.createElement("tbody", null, gdprDataRequestList.Data.map((dataRequest) => this.renderListDataRequest(dataRequest)))), this.renderPagination()) : /* @__PURE__ */ React__default.createElement("p", {
      className: "noData"
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "PersonalDataPage.noData"
    }, "No files available"))))))), openCancelDialog && /* @__PURE__ */ React__default.createElement(CancelConfirmDialog, {
      onCancel: () => this.setState({ openCancelDialog: false, selectedRequestDate: null }),
      onConfirm: () => this.cancelRequest(selectedRequestDate)
    }), openDownloadDialog && /* @__PURE__ */ React__default.createElement(DownloadConfirmDialog, {
      dateRequest: selectedRequestDate,
      onCancel: () => this.setState({ openDownloadDialog: false }),
      onConfirm: this.downloadGdpr
    }));
  }
}
const PersonalDataPageWithPropsGuard = withPropsGuard(PersonalDataPage, (prevProps, nextProps) => {
  return prevProps.page !== nextProps.page;
});
export { PersonalDataPageWithPropsGuard as default };
