from folkugat_web.dal.sql import Connection, get_connection
from folkugat_web.model import sessions as model

from . import conversion


def insert_session(session: model.Session, con: Connection | None = None):
    query = """
      INSERT INTO sessions
        (id, date, start_time, end_time, venue_name, venue_url, notes, cartell_url, is_live)
      VALUES
        (:id, :date, :start_time, :end_time, :venue_name, :venue_url, :notes, :cartell_url, :is_live)
      RETURNING *
    """
    data = conversion.session_to_row(session)
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, data)
        row: conversion.SessionRowTuple = cur.fetchone()
        return conversion.row_to_session(row)


def update_session(session: model.Session, con: Connection | None = None):
    query = """
      UPDATE sessions SET
        date = :date, start_time = :start_time, end_time = :end_time,
        venue_name = :venue_name, venue_url = :venue_url,
        notes = :notes, cartell_url = :cartell_url, is_live = :is_live
      WHERE id = :id
    """
    data = conversion.session_to_row(session)
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, data)


def delete_session_by_id(session_id: int, con: Connection | None = None):
    query = """
      DELETE FROM sessions
      WHERE id = :id
    """
    data = dict(id=session_id)
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, data)


def stop_live_sessions(con: Connection | None = None):
    query = """
      UPDATE sessions SET is_live = false WHERE is_live = true
    """
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query)


def set_live_session(session_id: int, con: Connection | None = None):
    query = """
      UPDATE sessions SET is_live = true WHERE id = :id
    """
    data = dict(id=session_id)
    with get_connection(con) as con:
        stop_live_sessions(con=con)
        cur = con.cursor()
        _ = cur.execute(query, data)
