<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 ConfigurationInputNumber from "@/components/displays/superuser/configuration/ConfigurationInputNumber.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.fxratesapi.config.enabled.get().then((response) => {
    console.log('FXRatesAPI enabled: ', response.data.data);
    enabled.value = response.data.data;
  }).catch((error) => {
    console.log(error);
  });
};

const getModuleConfig = async () => {
  await SessionUser.superUser.modules.fxratesapi.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();
};

load();

const showGetConversionRate = () => {
  // Get the conversion rate from DKK to other currencies
  // Show a sweet alert with a loader
  Swal.fire({
    title: 'Getting conversion rates from DKK',
    html: 'Please wait while we fetch the conversion rates from DKK to other currencies.',
    allowOutsideClick: () => !Swal.isLoading(),
    didOpen: () => {
      Swal.showLoading();
      // Get the conversion rate from DKK to other currencies
      SessionUser.superUser.modules.fxratesapi.functions.conversion_rate('DKK').then((response) => {
        console.log(response.data.data);
        console.log('Conversion rate from DKK to other currencies: ', response.data.data);
        // Show a success message
        Swal.fire({
          title: 'Conversion rates fetched successfully',
          text: 'The conversion rates have been fetched successfully.',
          icon: 'success',
          showConfirmButton: false,
          timer: 2000
        });
        return response.data.data;
      }).catch((error) => {
        console.log(error);
        Swal.hideLoading();
        Swal.showValidationMessage(
          `Request failed: ${error}`
        );
      });
    },
    showCancelButton: true,
    confirmButtonText: 'Get conversion rates',
  })
};

const showConversionRates = () => {
  // Get the conversion rates
  SessionUser.superUser.modules.fxratesapi.functions.conversion_rates().then((response) => {
    console.log(response.data.data);
    console.log('Conversion rates: ', response.data.data);
    // Show a success message
    Swal.fire({
      title: 'Conversion rates',
      html: '<pre>' + JSON.stringify(response.data.data, null, 2) + '</pre>',
      icon: 'info',
      showConfirmButton: true,
      confirmButtonText: 'OK'
    });
  }).catch((error) => {
    console.log(error);
  });
};
</script>

<template>
  <RestrictedPageWrapper :hasPermission="SessionUser.canAccessSuperUser()">
    <ConfigurationSubPageWrapper>
      <template #title>
        <PageTitle title="FXRatesAPI configuration" subtitle="The configuration of the FXRatesAPI integration" />
      </template>
      <template v-if="module_config.length > 0" #content>
        <ConfigurationCategory
          class="mt-2"
          module="FXRatesAPI"
          title="General settings"
          description="The general settings for the FXRatesAPI integration."
          icon="fas fa-cogs"
        >
        <ConfigurationSwitch
          class="mt-2"
          module="FXRatesAPI"
          title="Enable FXRatesAPI"
          description="Enable or disable the FXRatesAPI integration."
          icon="fas fa-cogs"
          :value="getModuleConfigValue('enabled') === true"
          :on-switch="SessionUser.superUser.modules.fxratesapi.config.enabled.set"
        />
        </ConfigurationCategory>
        <ConfigurationCategory
          class="mt-2"
          module="FXRatesAPI"
          title="API connection settings"
          description="The FXRatesAPI API connection settings."
          icon="fas fa-cogs"
        >
          <ConfigurationSecretKey
            class="mt-2"
            module="FXRatesAPI"
            title="Secret key (API key)"
            description="The secret key is used to authenticate the API connection."
            icon="fas fa-cogs"
            :isSet="getModuleConfigValue('secret_key') !== ''"
            :on-save="SessionUser.superUser.modules.fxratesapi.config.keys.secret_key.set"
          />
          <ConfigurationInputNumber
            class="mt-2"
            module="FXRatesAPI"
            title="Daily request limit"
            description="The daily request limit for the FXRatesAPI integration."
            icon="fas fa-cogs"
            :value="parseInt(getModuleConfigValue('daily_limit'))"
            :on-save="SessionUser.superUser.modules.fxratesapi.config.keys.daily_limit.set"
          />
        </ConfigurationCategory>
        <div class="buttons">
          <button class="button is-dark" @click="showGetConversionRate">
            <span class="icon">
              <i class="fas fa-sync"></i>
            </span>
            <span>Update conversion rates</span>
          </button>
          <button class="button is-dark" @click="showConversionRates">
            <span class="icon">
              <i class="fas fa-list"></i>
            </span>
            <span>Show conversion rates</span>
          </button>
        </div>
      </template>
    </ConfigurationSubPageWrapper>
  </RestrictedPageWrapper>
</template>

<style scoped>

</style>