<script setup>
import { getCurrentInstance, ref, onMounted, onUnmounted, nextTick, computed } from 'vue';
import GuestLayout from '../Layouts/GuestLayout.vue';
import { useForm } from '@inertiajs/inertia-vue3'

import EasyTable from "vue3-easy-data-table";
import axios from 'axios';

const headers = ref([
  { text: "Id", value: "id", sortable: true },
  { text: "Country", value: "country", sortable: true },
  { text: "Currency", value: "currency", sortable: true },
  { text: "Rate", value: "rate", sortable: true },
]);
const currencyCountryRate = ref([]);
const rates = ref([]);
const currencyHash = ref({});
const currency = ref([]);
const countryCurrency = ref([]);
const ccountry = ref([]);

const fetch_rates = async () => {
  try {
    var response = await axios.get(route('rates.index'));
    rates.value = response.data;
    response = await axios.get(route('ccountry.active'))
    ccountry.value = response.data

    currency.value = rates.value.map((currency) => currency.currency);
    countryCurrency.value = Object.fromEntries(
      rates.value.map((currency) => [currency.country_name, currency.currency])
    );
    currencyHash.value = Object.fromEntries(
      rates.value.map((currency) => [currency.currency, currency.rate]),
    );
    var i = 1;
    currencyCountryRate.value = ccountry.value.map((country) => {
      console.log(country);
      return { "country": country.country_name, "currency": country.currency_code, "rate": currencyHash.value[country.currency_code], "id": i++ }
    });
    currency.value.unshift('EUR');
    console.log("RATE=", rates.value);
    console.log('HASH=', currencyHash.value);
    console.log('CCC=',currencyCountryRate);
  } catch (e) {
    const response = await Swal.fire({
      title: __('are you want to try again') + '?',
      text: __(`${e}`),
      icon: 'question',
      showCancelButton: true,
      showCloseButton: true,
    })

    response.isConfirmed && fetch()
  }
}

onMounted(fetch_rates);

</script>

<template>
    <GuestLayout>
      <div class="flex flex-wrap gap-2 justify-center align-middle ">
    <div class="text-center grid-flow-col max-w-fit justify-items-center">
        <div class="font-extrabold">Exchange rates and coutry list</div>
        <div class="mt-5">
          <EasyTable :rows-per-page=30 :headers="headers" :items="currencyCountryRate" alternating :hide-footer="true"></EasyTable>
        </div>
    </div>
    </div>
  </GuestLayout>
</template>

<style>
@import 'vue3-easy-data-table/dist/style.css';
</style>
