import logging
from typing import Optional


from src.ezgg_lan_manager.services.DatabaseService import DatabaseService
from src.ezgg_lan_manager.services.TicketingService import TicketingService
from src.ezgg_lan_manager.types.ConfigurationTypes import LanInfo, SeatingConfiguration
from src.ezgg_lan_manager.types.Seat import Seat

logger = logging.getLogger(__name__.split(".")[-1])

class NoTicketError(Exception):
    pass

class SeatNotFoundError(Exception):
    pass

class WrongCategoryError(Exception):
    pass

class SeatAlreadyTakenError(Exception):
    pass

class SeatingService:
    def __init__(self, lan_info: LanInfo, db_service: DatabaseService, ticketing_service: TicketingService) -> None:
        self._lan_info = lan_info
        self._db_service = db_service
        self._ticketing_service = ticketing_service

    async def get_seating(self) -> list[Seat]:
        return await self._db_service.get_seating_info()

    async def get_seat(self, seat_id: str, cached_data: Optional[list[Seat]] = None) -> Optional[Seat]:
        all_seats = await self.get_seating() if not cached_data else cached_data
        for seat in all_seats:
            if seat.seat_id == seat_id:
                return seat

    async def get_user_seat(self, user_id: int) -> Optional[Seat]:
        all_seats = await self.get_seating()
        for seat in all_seats:
            if seat.user and seat.user.user_id == user_id:
                return seat

    async def seat_user(self, user_id: int, seat_id: str) -> None:
        user_ticket = await self._ticketing_service.get_user_ticket(user_id)
        if not user_ticket:
            raise NoTicketError

        seat = await self.get_seat(seat_id)
        if not seat:
            raise SeatNotFoundError

        if seat.category != user_ticket.category:
            raise WrongCategoryError

        if seat.user is not None:
            raise SeatAlreadyTakenError

        await self._db_service.seat_user(seat_id, user_id)

    # ToDo: Make function that creates database table `seats` from config
