from typing import Optional

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

from ._conversion import row_to_tema, tema_to_row
from .query import evict_tema_id_to_ngrams_cache


def insert_tema(tema: model.Tema, con: Optional[Connection] = None) -> model.Tema:
    query = """
      INSERT INTO temes
        (id, title, properties, links, lyrics, alternatives, ngrams,
         creation_date, modification_date, hidden)
      VALUES
        (:id, :title, :properties, :links, :lyrics, :alternatives, :ngrams,
         :creation_date, :modification_date, :hidden)
      RETURNING *
    """
    data = tema_to_row(tema)
    with get_connection(con) as con:
        cur = con.cursor()
        cur.execute(query, data)
        row = cur.fetchone()
        evict_tema_id_to_ngrams_cache()
        return row_to_tema(row)


def update_tema(tema: model.Tema, con: Optional[Connection] = None):
    query = """
      UPDATE temes
      SET
        title = :title, properties = :properties, links = :links, lyrics = :lyrics,
        alternatives = :alternatives, ngrams = :ngrams, creation_date = :creation_date,
        modification_date = :modification_date, hidden = :hidden
      WHERE
        id = :id
    """
    data = tema_to_row(tema)
    with get_connection(con) as con:
        cur = con.cursor()
        cur.execute(query, data)
        evict_tema_id_to_ngrams_cache()
        return
