from asyncio import sleep
from typing import Callable

from fastapi import HTTPException

from .config import Config
from .controllers import Controllers


async def stop_server(
    action: str, countdown: int, reason: str, timeout: int, then: Callable | None = None
):
    """Warns the players, stops the Server, and kills its process if its taking too long.

    Parameters:
        action (str): Action to write in the warning ("SERVER IS {action}...").
        countdown (int): Seconds to wait after the warning.
        reason: (str): The reason for the Server shutdown.
        timeout (int): Seconds to wait before killing the process.
        then (Callable | None) (default: None): Function to be called after the Server is stopped.
    """
    if countdown:
        Controllers.server.command(f"say SERVER IS {action} IN {countdown} SECONDS!!!")
        Controllers.server.command(f"say REASON: '{reason}'")
        while countdown > 0 and Controllers.server.status().get("players", {}).get(
            "online", 0
        ):
            await sleep(1)
            countdown -= 1

    # Controllers.server.command("stop")
    while timeout > 0 and Controllers.process.is_started():
        await sleep(1)
        timeout -= 1

    if Controllers.process.is_started():
        Controllers.process.kill()

    if then:
        then()


def check_password(password: str):
    if password != Config.MINECRAFTD_PASSWORD:
        raise HTTPException(401, "Password is invalid")
