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

from . import conversion


def insert_playlist_entry(pl_entry: model.PlaylistEntry, con: Connection | None = None) -> model.PlaylistEntry:
    query = """
      INSERT INTO playlists
        (id, session_id, set_id, tema_id)
      VALUES
        (:id, :session_id, :set_id, :tema_id)
      RETURNING *
    """
    data = conversion.playlist_entry_to_row(pl_entry)
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, data)
        row: conversion.PlaylistRowTuple = cur.fetchone()
        return conversion.row_to_playlist_entry(row)


def update_playlist_entry(entry: model.PlaylistEntry, con: Connection | None = None):
    query = """
      UPDATE playlists
      SET
        id = :id, session_id = :session_id, set_id = :set_id, tema_id = :tema_id
      WHERE
        id = :id
    """
    data = conversion.playlist_entry_to_row(entry)
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, data)
        return


def delete_playlist_entry(entry_id: int, con: Connection | None = None):
    query = """
      DELETE FROM playlists
      WHERE id = :id
    """
    data = dict(id=entry_id)
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, data)
        return


def delete_playlist_set(session_id: int, set_id: int, con: Connection | None = None):
    query = """
      DELETE FROM playlists
      WHERE session_id = :session_id AND set_id = :set_id
    """
    data = dict(session_id=session_id, set_id=set_id)
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, data)
        return
