import datetime
from datetime import date as Date
from typing import Optional

from folkugat_web.config import date as config
from folkugat_web.dal.sql import sessions as dal
from folkugat_web.model import sessions as model
from folkugat_web.model.sql import Order, OrderCol, Range


def get_date_names(date: Date) -> model.DateNames:
    return model.DateNames(
        day_name=config.DAY_NAMES_CAT[date.weekday()],
        day=str(date.day),
        month_name=config.MONTH_NAMES_CAT[date.month],
        year=str(date.year),
    )


def new_session() -> model.Session:
    sessions = get_sessions()
    if not sessions:
        venue = model.SessionVenue()
    else:
        venue = sessions[-1].venue
    return model.Session(venue=venue)


def get_sessions() -> list[model.Session]:
    return dal.get_sessions(order_by=OrderCol(model.SessionCols.DATE, Order.ASCENDING))


def get_next_sessions(limit: Optional[int] = None, offset: Optional[int] = None) -> list[model.Session]:
    return dal.get_sessions(
        date_range=Range(gte=datetime.date.today()),
        order_by=OrderCol(model.SessionCols.DATE, Order.ASCENDING),
        limit=limit,
        offset=offset,
    )


def get_sessions_history(limit: Optional[int] = None, offset: Optional[int] = None) -> list[model.Session]:
    return dal.get_sessions(
        date_range=Range(lt=datetime.date.today()),
        order_by=OrderCol(model.SessionCols.DATE, Order.DESCENDING),
        limit=limit,
        offset=offset,
    )


def get_next_session() -> Optional[model.Session]:
    return next(iter(get_next_sessions(limit=1,)), None)


def get_live_session() -> Optional[model.Session]:
    return next(iter(dal.get_sessions(is_live=True)), None)


def get_session(session_id: int) -> Optional[model.Session]:
    return next(iter(dal.get_sessions(session_id=session_id)), None)


def insert_session(session: model.Session):
    return dal.insert_session(session)


def set_session(session: model.Session):
    dal.update_session(session)


def delete_session(session_id: int):
    dal.delete_session_by_id(session_id)


def stop_live_sessions():
    dal.stop_live_sessions()


def set_live_session(session_id: int):
    dal.set_live_session(session_id=session_id)
