<script lang="ts">
  import {
    aniListLoggedIn,
    malLoggedIn,
    simklLoggedIn,
    watchlistNeedsRefresh,
    aniListPrimary,
    malPrimary,
    simklPrimary,
    malWatchList,
    simklWatchList,
  } from "./helperModules/GlobalVariablesAndHelperFunctions.svelte";
  import { onMount } from "svelte";
  import Router from "svelte-spa-router";
  import Home from "./routes/Home.svelte";
  import { wrap } from "svelte-spa-router/wrap";
  import Spinner from "./helperComponents/Spinner.svelte";
  import Header from "./helperComponents/Header.svelte";
  import { CheckIfAniListLoggedInAndLoadWatchList } from "./helperModules/CheckIfAniListLoggedInAndLoadWatchList.svelte";
  import { CheckIfMALLoggedInAndSetUser } from "./helperModules/CheckIfMyAnimeListLoggedIn.svelte";
  import { CheckIfSimklLoggedInAndSetUser } from "./helperModules/CheckIsSimklLoggedIn.svelte";
  import {
    CheckIfAniListLoggedIn,
    GetMyAnimeList,
    SimklGetUserWatchlist,
  } from "../wailsjs/go/main/App";
  import { loc } from "svelte-spa-router";

  onMount(async () => {
    let isAniListLoggedIn: boolean;
    let isMALLoggedIn: boolean;
    let isSimklLoggedIn: boolean;
    aniListLoggedIn.subscribe((value) => (isAniListLoggedIn = value));
    malLoggedIn.subscribe((value) => (isMALLoggedIn = value));
    simklLoggedIn.subscribe((value) => (isSimklLoggedIn = value));

    !isAniListLoggedIn && (await CheckIfAniListLoggedInAndLoadWatchList());
    !isMALLoggedIn && (await CheckIfMALLoggedInAndSetUser());
    !isSimklLoggedIn && (await CheckIfSimklLoggedInAndSetUser());
  });

  $: if ($loc?.location === "/" && $watchlistNeedsRefresh) {
    (async () => {
      if ($aniListLoggedIn && $aniListPrimary) {
        await CheckIfAniListLoggedInAndLoadWatchList();
      }
      if ($malLoggedIn && $malPrimary) {
        await GetMyAnimeList(1000).then((w) => malWatchList.set(w));
      }
      if ($simklLoggedIn && $simklPrimary) {
        await SimklGetUserWatchlist().then((w) => simklWatchList.set(w));
      }

      watchlistNeedsRefresh.set(false);
    })();
  }
</script>

<Header />
<Router
  routes={{
    "/": Home,
    "/anime/:id": wrap({
      asyncComponent: () => import("./routes/AnimeRoutePage.svelte"),
      conditions: [async () => await CheckIfAniListLoggedIn()],
      loadingComponent: Spinner,
    }),
    // '*': "Not Found"
  }}
/>
