Skip to content
Snippets Groups Projects
add-game-to-playing-list.tsx 2.79 KiB
"use client"

import { User } from "@prisma/client";
import { useRouter } from "next/navigation";
import { startTransition } from "react";
import { Button } from "./ui/button";

export default function AddGameToPlayingList(props: { gameId: string, user: User }) {

    const router = useRouter();
    const gameId = parseFloat(props.gameId);
    const user = props.user;

    let formData: {
        id: String;
        gameId: Number;
        add: boolean;
        planningGameList: number[] | undefined;
        playingGameList: number[] | undefined;
        finishedGameList: number[] | undefined;
    } = {
        id: "",
        gameId: -1,
        add: true,
        planningGameList: undefined,
        playingGameList: undefined,
        finishedGameList: undefined
    };

    async function removeGame(e: any) {
        e.preventDefault()

        formData.id = user.id;
        formData.playingGameList = props.user.playingGameList.filter((id) => id !== gameId)
        console.log(formData.playingGameList)
        const response = await fetch('/api/gamelists', {
            method: 'PUT',
            body: JSON.stringify(formData)
        })

        startTransition(() => {
            // Refresh the current route and fetch new data from the server without
            // losing client-side browser or React state.
            router.refresh();
        });
        return await response.json()
    }

    async function addGame(e: any) {
        e.preventDefault()

        formData.id = user.id;
        props.user.playingGameList.push(gameId)
        formData.playingGameList = props.user.playingGameList;
        const response = await fetch('/api/gamelists', {
            method: 'PUT',
            body: JSON.stringify(formData)
        })
        console.log("add game")
        startTransition(() => {
            // Refresh the current route and fetch new data from the server without
            // losing client-side browser or React state.
            router.refresh();
        });
        return await response.json()
    }


    let button = <div></div>;
    try {
        if (!props.user.playingGameList.includes(parseFloat(props.gameId))) {
            button = (
                <form onSubmit={addGame}>
                    <Button type="submit" size="lg">
                        Add Game To currently-playing-List
                    </Button>
                </form>
            )
        } else {
            button = (
                <form onSubmit={removeGame}>
                    <Button type="submit" size="lg" variant={"secondary"}>
                        Remove Game From currently-playing-List
                    </Button>
                </form>
            )
        }
    } catch (error) {
        // throw new Error("Failed to check playing-to-play-List");
    }

    return (
        button
    )
}