<script lang="ts" context="module">
    import {CheckIfAniListLoggedIn, GetAniListLoggedInUser, GetAniListUserWatchingList} from "../../wailsjs/go/main/App";
    import {MediaListSort} from "../anilist/types/AniListTypes";
    import { aniListUser, watchListPage, animePerPage, aniListPrimary, aniListLoggedIn, aniListWatchlist } from "./GlobalVariablesAndHelperFunctions.svelte"

    let isAniListPrimary: boolean
    let page: number
    let perPage: number

    aniListPrimary.subscribe(value => isAniListPrimary = value)
    watchListPage.subscribe(value => page = value)
    animePerPage.subscribe(value => perPage = value)

    export const LoadAniListUser = async () => {
        await GetAniListLoggedInUser().then(user => {
            aniListUser.set(user)
        })
    }

    export const LoadAniListWatchList = async () => {
        await GetAniListUserWatchingList(page, perPage, MediaListSort.UpdatedTimeDesc).then((watchList) => {
            aniListWatchlist.set(watchList)
        })
    }

    export const CheckIfAniListLoggedInAndLoadWatchList = async () => {
        const loggedIn = await CheckIfAniListLoggedIn()
        if (loggedIn) {
            await LoadAniListUser()
            if (isAniListPrimary) await LoadAniListWatchList()
        }
        aniListLoggedIn.set(loggedIn)
    }
</script>