import datetime
from datetime import date as Date

from folkugat_web.config import date as config
from folkugat_web.dal.sql.sessions import query, write
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 query.get_sessions(order_by=OrderCol(model.SessionCols.DATE, Order.ASCENDING))


def get_next_sessions(limit: int | None = None, offset: int | None = None) -> list[model.Session]:
    return query.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: int | None = None, offset: int | None = None) -> list[model.Session]:
    return query.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() -> model.Session | None:
    return next(iter(get_next_sessions(limit=1,)), None)


def get_live_session() -> model.Session | None:
    return next(iter(query.get_sessions(is_live=True)), None)


def get_session(session_id: int) -> model.Session | None:
    return next(iter(query.get_sessions(session_id=session_id)), None)


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


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


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


def stop_live_sessions():
    write.stop_live_sessions()


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