<template>
  <v-app>
    <v-container class="mb-7" fluid style="width: 1440px">
      <main-nav />

      <v-main>
        <build-server-stats />
        <currently-building />
        <packages />
      </v-main>
    </v-container>
  </v-app>
</template>

<script lang="ts" setup>
import MainNav from '@/components/MainNav.vue'
import BuildServerStats from '@/components/BuildServerStats.vue'
import CurrentlyBuilding from '@/components/CurrentlyBuilding.vue'
import Packages from '@/components/Packages.vue'
import { useStatsStore } from '@/stores/statsStore'
import { onBeforeMount, onUnmounted } from 'vue'
import { usePackagesStore } from '@/stores'

const statsStore = useStatsStore()
const packagesStore = usePackagesStore()

let refreshInterval: number | null = null
const startAutoRefresh = (intervalMinutes = Number(import.meta.env.VITE_UPDATE_INTERVAL) || 5) => {
  stopAutoRefresh()
  refreshInterval = window.setInterval(
    () => {
      statsStore.fetchStats()
      packagesStore.fetchPackages()
      packagesStore.fetchCurrentlyBuilding()
    },
    intervalMinutes * 60 * 1000
  )
}

const stopAutoRefresh = () => {
  if (refreshInterval !== null) {
    clearInterval(refreshInterval)
    refreshInterval = null
  }
}

onBeforeMount(() => {
  statsStore.fetchStats()
  packagesStore.fetchPackages(true)
  packagesStore.fetchCurrentlyBuilding()
  startAutoRefresh()
})

onUnmounted(() => {
  stopAutoRefresh()
})
</script>
