<script setup lang="ts">
import { ref, onMounted, onUpdated, nextTick, onBeforeMount } from "vue";
import { createIcons, icons } from "lucide";
import { WhoIs } from "./lib/whois";
import { DomainFactory } from "./lib/factory";

const visible = ref<boolean>(false);
const whois = ref<WhoIs>(new WhoIs());
const factory = ref<DomainFactory>(new DomainFactory());
const domain = ref<string | null>(null);
const domainAvailable = ref<boolean | null>(null);
const lang = ref<string>("english");
const loading = ref<boolean>(true);
const fetching = ref<boolean>(false);
const error = ref<string | null>(null);

function newDomain() {
  if (!factory.value.error) {
    fetching.value = true;
    factory.value
      .next(lang.value)
      .then((value) => {
        domain.value = value;
        checkAvailability();
      })
      .catch((err: unknown) => {
        throw err;
      });
  }
}

function checkAvailability() {
  domainAvailable.value = null;
  if (!whois.value.error && domain.value) {
    whois.value
      .isDomainAvailable(domain.value)
      .then((available) => {
        domainAvailable.value = available;
        fetching.value = false;
        if (!available) {
          newDomain();
        }
      })
      .catch((err: unknown) => {
        throw err;
      });
  }
}

onBeforeMount(async () => {
  await whois.value.init();
  await factory.value.init();
  newDomain();
  loading.value = false;
});
onMounted(() => {
  setTimeout(() => {
    visible.value = true;
  });
});
onUpdated(async () => {
  await nextTick();
  createIcons({
    icons,
    nameAttr: "icon",
    attrs: {
      width: "1.1em",
      height: "1.1em",
    },
  });
});
</script>

<template>
  <main :style="{ display: visible ? 'inherit' : 'none' }">
    <h1>
      <span v-show="fetching || loading"><i icon="cog"></i></span>
      {{ domain }}
      <span v-show="!loading"
        >({{
          domainAvailable === null
            ? "?"
            : domainAvailable
              ? "available"
              : "unavailable"
        }})</span
      >
    </h1>
    <button v-show="!loading && !fetching" @click="newDomain">
      New domain
    </button>
    <span v-if="error">Error: {{ error }}</span>
  </main>
</template>

<style scoped>
.footer {
  opacity: 50%;
}
</style>
