<script setup>
import PageTitle from "@/components/global/PageTitle.vue";
import RestrictedPageWrapper from "@/components/page/wrappers/RestrictedPageWrapper.vue";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
import { useRouter } from 'vue-router'
import { ref } from 'vue';
import { ConfigurationSelectOption } from "@/components/displays/superuser/configuration/ConfigurationSelectObject.vue";
import ConfigurationSubPageWrapper
  from "@/views/dashboards/superUserDashboard/configuration/ConfigurationSubPageWrapper.vue";
import ConfigurationCategory from "@/components/displays/superuser/configuration/ConfigurationCategory.vue";
import ConfigurationSwitch from "@/components/displays/superuser/configuration/ConfigurationSwitch.vue";
import ConfigurationSelect from "@/components/displays/superuser/configuration/ConfigurationSelect.vue";
import ConfigurationSecretKey from "@/components/displays/superuser/configuration/ConfigurationSecretKey.vue";
import ConfigurationInput from "@/components/displays/superuser/configuration/ConfigurationInput.vue";
import Swal from "sweetalert2";

// Get the department from the route
const router = useRouter()

const enabled = ref(false);
const module_config = ref([]);

const getEnabled = async () => {
  await SessionUser.superUser.modules.email.config.enabled.get().then((response) => {
    enabled.value = response.data.data;
  }).catch((error) => {
    console.log(error);
  });
};

const getModuleConfig = async () => {
  await SessionUser.superUser.modules.email.config.get_all().then((response) => {
    let tmp_module_config = response.data.data;
    let tmp_module_config_array = [];
    for (const [key, value] of Object.entries(tmp_module_config)) {
      console.log(`${value.variable}: ${value.value}`);
      tmp_module_config_array.push({
        variable: value.variable,
        value: value.value,
      });
    }
    module_config.value = tmp_module_config_array;
    console.log(module_config.value);
  }).catch((error) => {
    console.log(error);
  });
};

const getModuleConfigValue = (variable) => {
  const config = module_config.value.find((config) => config.variable === variable);
  // Log to the console, what the value was found
  if (config) {
    console.log(`Found value for ${variable}: ${config.value}`);
  } else {
    console.log(`No value found for ${variable}`);
  }
  return config ? config.value : '';
};

const load = async () => {
  await getModuleConfig();
};

const encryptionOptions = [
  { value: 'ssl', label: 'SSL' },
  { value: 'tls', label: 'TLS' },
  { value: 'starttls', label: 'STARTTLS' },
  { value: 'none', label: 'None' },
];

const showSendTestEmail = async () => {
  await Swal.fire({
    title: 'Send test email',
    text: 'Please enter the email address you want to send the test email to.',
    input: 'email',
    inputAttributes: {
      autocapitalize: 'off'
    },
    showCancelButton: true,
    confirmButtonText: 'Send',
    showLoaderOnConfirm: true,
    preConfirm: (email) => {
      return SessionUser.superUser.modules.email.sendTestEmail(email)
          .then((response) => {
            Swal.fire({
              title: 'Test email sent',
              text: 'The test email has been sent to the email address.',
              icon: 'success',
            });
          })
          .catch((error) => {
            Swal.fire({
              title: 'Error',
              text: 'An error occurred while sending the test email.',
              icon: 'error',
            });
          });
    },
    allowOutsideClick: () => !Swal.isLoading()
  });
};

load();
</script>

<template>
  <RestrictedPageWrapper :hasPermission="SessionUser.canAccessSuperUser()">
    <ConfigurationSubPageWrapper>
      <template #title>
        <PageTitle title="Email configuration" subtitle="The configuration of the email system."/>
      </template>
      <template v-if="module_config.length > 0" #content>
        <ConfigurationCategory
          class="mt-2"
          module="Email"
          title="General settings"
          description="The general settings for the email system."
          icon="fas fa-cogs"
        >
        <ConfigurationSwitch
          class="mt-2"
          module="Email"
          title="Enable email system"
          description="Enable or disable the email system."
          icon="fas fa-cogs"
          :value="getModuleConfigValue('enabled') === true"
          :on-switch="SessionUser.superUser.modules.email.config.enabled.set"
        />
          <button class="button is-dark mt-2" @click="showSendTestEmail()">Send test email</button>
        </ConfigurationCategory>
        <!-- Sender identity -->
        <ConfigurationCategory
          class="mt-2"
          module="Email"
          title="Sender identity"
          description="The sender identity settings for the email system."
          icon="fas fa-cogs"
        >
          <ConfigurationInput
              class="mt-2"
              module="Email"
              title="From email address"
              description="The email address that the email is sent from. E.g. johndoe@gmail.com"
              icon="fas fa-cogs"
              :value="getModuleConfigValue('smtp_from')"
              :on-save="SessionUser.superUser.modules.email.config.keys.smtp_from.set"
          />
          <ConfigurationInput
              class="mt-2"
              module="Email"
              title="From name"
              description="The name that the email is sent from. E.g. John Doe"
              icon="fas fa-cogs"
              :value="getModuleConfigValue('smtp_from_name')"
              :on-save="SessionUser.superUser.modules.email.config.keys.smtp_from_name.set"
          />
          <ConfigurationInput
              class="mt-2"
              module="Email"
              title="Reply to email address"
              description="The email address that the email is replied to. E.g. support@company.com"
              icon="fas fa-cogs"
              :value="getModuleConfigValue('smtp_reply_to')"
              :on-save="SessionUser.superUser.modules.email.config.keys.smtp_reply_to.set"
          />
          <ConfigurationInput
              class="mt-2"
              module="Email"
              title="Reply to name"
              description="The name that the email is replied to. E.g. Support"
              icon="fas fa-cogs"
              :value="getModuleConfigValue('smtp_reply_to_name')"
              :on-save="SessionUser.superUser.modules.email.config.keys.smtp_reply_to_name.set"
          />
        </ConfigurationCategory>
        <ConfigurationCategory
          v-if="!getModuleConfigValue('mailersend_enabled')"
          class="mt-2"
          module="Email"
          title="SMTP settings"
          description="The SMTP settings for the email system."
          icon="fas fa-cogs"
        >
          <ConfigurationInput
            class="mt-2"
            module="Email"
            title="SMTP host"
            description="The SMTP host is the server that sends the email. This is usually the mail server."
            icon="fas fa-cogs"
            :value="getModuleConfigValue('smtp_host')"
            :on-save="SessionUser.superUser.modules.email.config.keys.smtp_host.set"
          />
          <ConfigurationInput
            class="mt-2"
            module="Email"
            title="SMTP port"
            description="The SMTP port is the port that the SMTP host uses to send the email."
            icon="fas fa-cogs"
            :value="getModuleConfigValue('smtp_port')"
            :on-save="SessionUser.superUser.modules.email.config.keys.smtp_port.set"
          />
          <ConfigurationInput
            class="mt-2"
            module="Email"
            title="SMTP username"
            description="The SMTP username is the username that the SMTP host uses to send the email."
            icon="fas fa-cogs"
            :value="getModuleConfigValue('smtp_username')"
            :on-save="SessionUser.superUser.modules.email.config.keys.smtp_username.set"
          />
          <ConfigurationSecretKey
            class="mt-2"
            module="Email"
            title="SMTP password"
            description="The SMTP password is the password that the SMTP host uses to send the email."
            icon="fas fa-cogs"
            :is-set="getModuleConfigValue('smtp_password') !== ''"
            :on-save="SessionUser.superUser.modules.email.config.keys.smtp_password.set"
          />

          <ConfigurationSelect
            class="mt-2"
            module="Email"
            title="SMTP encryption"
            description="The SMTP encryption is the encryption that the SMTP host uses to send the email."
            icon="fas fa-cogs"
            :options="encryptionOptions"
            :value="getModuleConfigValue('smtp_encryption')"
            :on-select="SessionUser.superUser.modules.email.config.keys.smtp_encryption.set"
          />

        </ConfigurationCategory>
        <ConfigurationCategory
          class="mt-2"
          module="Email"
          title="Mailersend integration"
          description="The Mailersend integration settings."
          icon="fas fa-cogs"
        >
          <ConfigurationSwitch
            class="mt-2"
            module="Email"
            title="Enable Mailersend"
            description="Enable or disable the Mailersend integration."
            icon="fas fa-cogs"
            :value="getModuleConfigValue('mailersend_enabled') === true"
            :onSwitch="SessionUser.superUser.modules.email.config.keys.mailersend_enabled.set"
          />
          <ConfigurationSecretKey
            class="mt-2"
            module="Email"
            title="Mailersend API key"
            description="The Mailersend API key is used to authenticate the Mailersend integration."
            icon="fas fa-cogs"
            :is-set="getModuleConfigValue('mailersend_api_key') !== ''"
            :on-save="SessionUser.superUser.modules.email.config.keys.mailersend_api_key.set"
          />
        </ConfigurationCategory>
      </template>
    </ConfigurationSubPageWrapper>
  </RestrictedPageWrapper>
</template>

<style scoped>

</style>