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

`;
    if (i += `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 (
`, i += `${e.createdBy}, current_date, ${e.createdBy}, current_date, `, i += e.day !== void 0 && e.day !== null ? `${e.day}, ` : "null, ", i += e.description ? `'${e.description.replace(/'/g, "''")}', ` : "null, ", i += `'${e.eventType}', `, i += e.eventTypeDetailId !== void 0 && e.eventTypeDetailId !== null ? `${e.eventTypeDetailId}, ` : "null, ", i += e.formTypeId !== void 0 && e.formTypeId !== null ? `${e.formTypeId}, ` : "null, ", i += e.hour !== void 0 && e.hour !== null ? `${e.hour}, ` : "null, ", i += e.minute !== void 0 && e.minute !== null ? `${e.minute}, ` : "null, ", i += `'${e.name.replace(/'/g, "''")}', `, i += `'${e.configJson.replace(/'/g, "''")}', `, i += `'${e.state}', `, i += e.trigerWhen !== void 0 && e.trigerWhen !== null ? `'${e.trigerWhen}', ` : "null, ", i += e.eventTypeDetailCode !== void 0 && e.eventTypeDetailCode !== null ? `${e.eventTypeDetailCode}, ` : "null, ", i += `'${e.uuid}');
`, e.eventType === "TIMMER_BASED" && e.state !== "INACTIVE") {
      let a = v();
      switch (e.trigerWhen) {
        case "MONTHLY":
          a.add(1, "months").set({
            date: e.day,
            hour: e.hour || 0,
            minute: e.minute || 0,
            second: 0
          });
          break;
        case "DAILY":
          a.add(E(e), "days").set({
            hour: e.hour || 0,
            minute: e.minute || 0,
            second: 0
          });
          break;
        case "HOURLY":
          a.add(1, "hours").set({ minute: E(e), second: 0 });
          break;
        case "MINUTE":
          a.add(e.minute, "minutes").set({ second: 0 });
          break;
      }
      i += `
DELETE FROM TIMER_EVENT WHERE event_config_uuid = '${e.uuid}' AND status = 'NEW';

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