import { jsxs as N, Fragment as J, jsx as o } from "react/jsx-runtime";
import { useState as c, useCallback as L, useEffect as U } from "react";
import u from "prop-types";
import { Dialog as W, DialogTitle as k, DialogContent as B, TextField as V, DialogActions as P, Button as w } from "@mui/material";
import { showToast as I } from "@/common/toaster/toaster";
import j from "@/views/custom-components/CustomConfirmationModal";
import C from "moment/moment";
import f from "@/hooks/useTrackEvent";
import { useTranslateProvider as z } from "@/common/languageTranslator/TranslationContext";
const H = ({ configuredQuery: t, open: O, onClose: m, dataTestId: F }) => {
  const [r, S] = c(""), [T, R] = c(!1), { translate: _ } = z(), [y, p] = c(!1), M = L(() => {
    var n;
    const l = (n = t == null ? void 0 : t.configJson) == null ? void 0 : n.includes("public");
    R(l);
    let e = `DELETE FROM EVENT_CONFIGURATION WHERE uuid = '${t.uuid}';

`;
    if (e += `INSERT INTO EVENT_CONFIGURATION (created_by, created_on, modified_by, modified_on, day, description, event_type, event_type_detail_id, form_type_id, hour, minute, name, config_json, state, trigger_when, event_type_detail_code, uuid)
VALUES (
`, e += `${t.createdBy}, current_date, ${t.createdBy}, current_date, `, e += t.day !== void 0 && t.day !== null ? `${t.day}, ` : "null, ", e += t.description ? `'${t.description.replace(/'/g, "''")}', ` : "null, ", e += `'${t.eventType}', `, e += t.eventTypeDetailId !== void 0 && t.eventTypeDetailId !== null ? `${t.eventTypeDetailId}, ` : "null, ", e += t.formTypeId !== void 0 && t.formTypeId !== null ? `${t.formTypeId}, ` : "null, ", e += t.hour !== void 0 && t.hour !== null ? `${t.hour}, ` : "null, ", e += t.minute !== void 0 && t.minute !== null ? `${t.minute}, ` : "null, ", e += `'${t.name.replace(/'/g, "''")}', `, e += `'${t.configJson.replace(/'/g, "''")}', `, e += `'${t.state}', `, e += t.trigerWhen !== void 0 && t.trigerWhen !== null ? `'${t.trigerWhen}', ` : "null, ", e += t.eventTypeDetailCode !== void 0 && t.eventTypeDetailCode !== null ? `${t.eventTypeDetailCode}, ` : "null, ", e += `'${t.uuid}');
`, t.eventType === "TIMMER_BASED" && t.state !== "INACTIVE") {
      let s = C();
      switch (t.trigerWhen) {
        case "MONTHLY":
          s.add(1, "months").set({
            date: t.day,
            hour: t.hour || 0,
            minute: t.minute || 0,
            second: 0
          });
          break;
        case "DAILY":
          s.add($(t), "days").set({
            hour: t.hour || 0,
            minute: t.minute || 0,
            second: 0
          });
          break;
        case "HOURLY":
          s.add(1, "hours").set({ minute: $(t), second: 0 });
          break;
        case "MINUTE":
          s.add(t.minute, "minutes").set({ second: 0 });
          break;
      }
      e += `
DELETE FROM TIMER_EVENT WHERE event_config_uuid = '${t.uuid}' AND status = 'NEW';

`, e += `INSERT INTO timer_event (event_config_uuid, processed, status, type, system_trigger_on)
VALUES (
`, e += `'${t.uuid}', false, 'NEW', 'TIMER_EVENT', '${s.format("MM-DD-yyyy HH:mm:ss")}');
`;
    }
    if (t.configJson !== null) {
      const s = JSON.parse(t.configJson);
      let D = !0;
      s.forEach((E) => {
        E.conditions !== null && E.conditions.length > 0 && E.conditions.forEach((h) => {
          h.notificaitonConfigsType !== null && h.notificaitonConfigsType.length > 0 && (D && (e += `
DELETE FROM EVENT_CONFIGURATION_TYPE WHERE event_config_uuid = '${t.uuid}';
`, D = !1), h.notificaitonConfigsType.forEach((a) => {
            e += `
INSERT INTO EVENT_CONFIGURATION_TYPE (id, base_date_field_name, event_config_uuid, day, email_subject, email_subject_parameter, hour, minute, mobile_notification_type, template, template_parameter, triger_when, type, user_field_name, family_field_name, member_field_name, query_master_id, query_master_param_json, query_code, sms_config_json, push_notification_config_json)
VALUES (
`, e += `'${a.id}', `, e += a.baseDateFieldName ? `'${a.baseDateFieldName}', ` : "null, ", e += `'${t.uuid}', `, e += a.day !== void 0 && a.day !== null ? `${a.day}, ` : "null, ", e += a.emailSubject ? `'${a.emailSubject.replace(/'/g, "''")}', ` : "null, ", e += a.emailSubjectParameter ? `'${a.emailSubjectParameter}', ` : "null, ", e += a.hour !== void 0 && a.hour !== null ? `${a.hour}, ` : "null, ", e += a.miniute !== void 0 && a.miniute !== null ? `${a.miniute}, ` : "null, ", e += a.mobileNotificationType !== void 0 && a.mobileNotificationType !== null ? `${a.mobileNotificationType}, ` : "null, ", e += a.template ? `'${a.template.replace(/'/g, "''")}', ` : "null, ", e += a.templateParameter ? `'${a.templateParameter.replace(/'/g, "''")}', ` : "null, ", e += a.trigerWhen ? `'${a.trigerWhen}', ` : "null, ", e += a.type ? `'${a.type}', ` : "null, ", e += a.userFieldName ? `'${a.userFieldName}', ` : "null, ", e += a.familyFieldName ? `'${a.familyFieldName}', ` : "null, ", e += a.memberFieldName ? `'${a.memberFieldName}', ` : "null, ", e += a.queryMasterId !== void 0 && a.queryMasterId !== null ? `${a.queryMasterId}, ` : "null, ", e += a.queryMasterParamJson !== void 0 && a.queryMasterParamJson !== null ? `'${JSON.stringify(a.queryMasterParamJson).replace(/'/g, "''")}', ` : "null, ", e += a.queryCode ? `'${a.queryCode}', ` : "null, ", e += a.smsConfigJson !== void 0 && a.smsConfigJson !== null ? `'${JSON.stringify(a.smsConfigJson).replace(/'/g, "''")}', ` : "null, ", e += a.pushNotificationConfigJson !== void 0 && a.pushNotificationConfigJson !== null ? `'${JSON.stringify(a.pushNotificationConfigJson).replace(/'/g, "''")}'` : "null", e += `);
`, a.mobileNotificationConfigs && a.mobileNotificationConfigs.length > 0 && (e += `
DELETE FROM EVENT_MOBILE_CONFIGURATION WHERE notification_type_config_id = '${a.id}';
`, a.mobileNotificationConfigs.forEach(
              (d) => {
                e += `
INSERT INTO EVENT_MOBILE_CONFIGURATION (id, notification_code, notification_type_config_id, number_of_days_added_for_due_date, number_of_days_added_for_expiry_date, number_of_days_added_for_on_date)
VALUES (
`, e += `'${d.id}', '${d.notificationCode}', '${d.notificationTypeConfigId}', ${d.numberOfDaysAddedForDueDate}, ${d.numberOfDaysAddedForExpiryDate}, ${d.numberOfDaysAddedForOnDate});
`;
              }
            ));
          }));
        });
      });
    }
    let i = {
      id: t.id,
      name: t.name,
      description: t.description,
      eventType: t.eventType,
      eventTypeDetailId: t.eventTypeDetailId,
      formTypeId: t.formTypeId,
      eventTypeDetailCode: t.eventTypeDetailCode,
      trigerWhen: t.trigerWhen,
      day: t.day,
      hour: t.hour,
      minute: t.minute,
      state: t.state,
      createdBy: t.createdBy,
      createdOn: C().valueOf(),
      notificationConfigDetails: JSON.parse(t.configJson),
      status: null,
      completionTime: null,
      configJson: null,
      uuid: t.uuid
    };
    e += `
INSERT INTO SYNC_SYSTEM_CONFIGURATION_MASTER (feature_type, config_json, created_on, created_by, feature_uuid, feature_name)
VALUES (
`, e += `'EVENT_BUILDER', '${JSON.stringify(i).replace(/'/g, "''")}', current_date, ${t.createdBy}, '${t.uuid}', '${t.name}');
`, S(e);
  }, [t]), $ = function(l) {
    const e = /* @__PURE__ */ new Date();
    return new Date(
      e.getFullYear(),
      e.getMonth(),
      e.getDate(),
      l.hour,
      l.minute
    ) > e ? 0 : 1;
  }, x = () => {
    var l;
    (l = navigator == null ? void 0 : navigator.clipboard) == null || l.writeText(r).then(() => {
      I({ message: "Query Copied", type: "success" }), m();
    });
  }, A = () => {
    v(), p((l) => !l);
  }, b = f(), v = async () => {
    if (window.showSaveFilePicker)
      try {
        const l = {
          suggestedName: `V${(/* @__PURE__ */ new Date()).getTime()}__CHANGE_IN_${t.code}.sql`,
          types: [
            {
              description: "SQL Files",
              accept: { "text/plain": [".sql"] }
            }
          ]
        }, e = await window.showSaveFilePicker(l), i = await e.createWritable();
        await i.write(r), await i.close();
        const n = (new Blob([r], { type: "text/plain" }).size / 1024).toFixed(2);
        b("file_download", {
          file_type: "sql",
          file_name: e.name,
          file_size: `${n} KB`,
          download_status: "success"
        }), I({
          message: "Query Downloaded SuccessFully",
          type: "success"
        }), m();
      } catch (l) {
        console.error("Something went wrong while downloading: ", l);
      }
    else {
      const l = new Blob([r], { type: "text/plain" }), e = (l.size / 1024).toFixed(2), i = URL.createObjectURL(l), n = document.createElement("a");
      n.href = i, n.download = `V${(/* @__PURE__ */ new Date()).getTime()}__CHANGE_IN_${t.code}.sql`, document.body.appendChild(n), n.click(), b("file_download", {
        file_type: "sql",
        file_name: n.download,
        file_size: `${e} KB`,
        download_status: "success"
      }), document.body.removeChild(n), URL.revokeObjectURL(i), I({ message: "Query Downloaded SuccessFully", type: "success" }), m();
    }
  }, q = () => {
    T ? p((l) => !l) : v();
  };
  return U(() => {
    t && M();
  }, [t]), /* @__PURE__ */ N(J, { children: [
    /* @__PURE__ */ o(
      j,
      {
        description: "This Flyway contains keyword 'public'. Are you sure you want to download?",
        title: "CONFIRM ACTION",
        handleClick: A,
        open: y,
        handleClose: () => p((l) => !l),
        dataTestId: "showflywayquery-customconfirmationmodal-confirmation-modal"
      }
    ),
    /* @__PURE__ */ N(
      W,
      {
        open: O,
        onClose: m,
        fullWidth: !0,
        maxWidth: "md",
        "data-testid": F,
        children: [
          /* @__PURE__ */ o(k, { className: "font-medium text-lg border-b p-2.5 px-5", children: _("Flyway Query") }),
          /* @__PURE__ */ o(B, { children: /* @__PURE__ */ o(
            V,
            {
              multiline: !0,
              rows: 10,
              variant: "outlined",
              fullWidth: !0,
              value: r,
              sx: {
                "& .MuiInputBase-input": {
                  fontSize: "14px"
                },
                "& .MuiOutlinedInput-root": {
                  // fontSize: '14px'
                  borderRadius: "5px"
                }
              },
              slotProps: {
                input: {
                  readOnly: !0
                }
              },
              "data-testid": "showflywayquery-textfield-query-display"
            }
          ) }),
          /* @__PURE__ */ N(P, { children: [
            /* @__PURE__ */ o(
              w,
              {
                onClick: q,
                variant: "contained",
                size: "small",
                color: "primary",
                "data-testid": "showflywayquery-button-download-action",
                children: _("Download")
              }
            ),
            /* @__PURE__ */ o(
              w,
              {
                onClick: x,
                variant: "contained",
                size: "small",
                color: "primary",
                "data-testid": "showflywayquery-button-copyquery-action",
                children: _("Copy Query")
              }
            ),
            /* @__PURE__ */ o(
              w,
              {
                onClick: m,
                variant: "contained",
                color: "secondary",
                size: "small",
                "data-testid": "showflywayquery-button-cancel-action",
                children: _("Cancel")
              }
            )
          ] })
        ]
      }
    )
  ] });
};
H.propTypes = {
  configuredQuery: u.any,
  open: u.any,
  onClose: u.any,
  dataTestId: u.any
};
export {
  H as default
};
//# sourceMappingURL=ShowFlywayQuery-DVRCd384.js.map
