import json

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

from . import conversion
from .query import evict_tema_id_to_ngrams_cache


def insert_tema(tema: model.Tema, con: Connection | None = None) -> model.Tema:
    query = """
      INSERT INTO temes
        (id, title, alternatives, creation_date, modification_date, hidden)
      VALUES
        (:id, :title, :alternatives, :creation_date, :modification_date, :hidden)
      RETURNING id, title, alternatives, creation_date, modification_date, hidden
    """
    data = conversion.tema_to_row(tema)
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, data)
        row: conversion.TemaRowTuple = cur.fetchone()
        evict_tema_id_to_ngrams_cache()
        return conversion.row_to_tema(row)


def update_tema(tema: model.Tema, con: Connection | None = None):
    query = """
      UPDATE temes
      SET
        title = :title, alternatives = :alternatives, creation_date = :creation_date,
        modification_date = :modification_date, hidden = :hidden
      WHERE
        id = :id
    """
    data = conversion.tema_to_row(tema)
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, data)
        return


def update_ngrams(tema: model.Tema, con: Connection | None = None):
    query = """
      UPDATE temes
      SET
        ngrams = :ngrams
      WHERE
        id = :id
    """
    data = dict(id=tema.id, ngrams=json.dumps(tema.ngrams()))
    with get_connection(con) as con:
        cur = con.cursor()
        _ = cur.execute(query, data)
        evict_tema_id_to_ngrams_cache()
        return


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