#
# Copyright (c) 2025, mstoeck3
# All rights reserved.
#
# This source code is licensed under the BSD-3-Clause license found in the
# LICENSE file in the root directory of this source tree.
#

import sqlite3
import os
from dotenv import dotenv_values
DB_DIR = "app_database"
DB_FILE = os.path.join(DB_DIR, "management_db.sqlite")

class DatabaseService():
    def __init__(self) -> None:
        print("DBSV: INITIALIZE DATABASE")
        self.conn = self.connect_db()
    
    def connect_db(self) -> sqlite3.Connection:
        os.makedirs(DB_DIR, exist_ok=True)
        try:
            conn = sqlite3.connect(DB_FILE)
            print("DBSV: DATABASE AVAILABLE")
            return conn
        except sqlite3.Error as e:
            raise

    def check_exist(self) -> bool:
        if os.path.exists(DB_FILE):
            print("DBSV: DATABASE EXISTS")
            return True
        else:
            return False
    
class AppSettings(DatabaseService):
    def __init__(self)->None:
        print("DBSV:APPSETTINGS: SETTINGS AVAILABLE")
        self.conn = self.connect_db()
        self.create_initial_configs()
        
    def check_exist(self):
        try:
            with self.conn as conn:
                cur = conn.cursor()
                statement = """
                SELECT key,val FROM settings;      
                """
                cur.execute(statement)
                rows = cur.fetchall()
                if len(rows)==6:  # expecting 6 initial settings
                    print("DBSV:APPSETTINGS: SETTINGS EXIST")
                    return True
                else:
                    return False
        except sqlite3.DatabaseError as e:
            print("DBSV: DB NOT FOUND. CREATING...")
            return e

    def create_initial_configs(self)->None:
        if self.check_exist()==True:
            
            return
        else:
            print("DBSV:APPSETTINGS: CREATING INITIAL SETTINGS")
            initial_config =dotenv_values()
            with self.conn as conn:
                cur = conn.cursor()
                statement = """
                CREATE TABLE IF NOT EXISTS settings (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    key text NOT NULL,
                    val text NOT NULL
                );
                """
                cur.execute(statement)
                for key,val in initial_config.items():
                    task = (key,val)
                    statement = f"""
                    INSERT INTO settings(key,val) VALUES(?,?);
                    """
                    cur.execute(statement, task)
            conn.commit()
    