from typing import Optional

from folkugat_web import data
from folkugat_web.dal.sql import Connection, get_connection

from .write import insert_tema


def create_db(con: Optional[Connection] = None):
    with get_connection(con) as con:
        drop_temes_table(con)
        create_temes_table(con)

        for tema in data.TEMES:
            insert_tema(tema, con)


def drop_temes_table(con: Connection):
    query = "DROP TABLE IF EXISTS temes"
    cur = con.cursor()
    cur.execute(query)


def create_temes_table(con: Connection):
    query = """
      CREATE TABLE IF NOT EXISTS temes (
        id INTEGER PRIMARY KEY,
        title TEXT NOT NULL,
        properties TEXT,
        links TEXT,
        lyrics TEXT,
        alternatives TEXT,
        ngrams TEXT,
        creation_date TEXT NOT NULL,
        modification_date TEXT NOT NULL,
        hidden INTEGER NOT NULL
    )
    """
    cur = con.cursor()
    cur.execute(query)
