//created by thschleicher

import * as SQLite from "expo-sqlite";
import uuid from "react-native-uuid";

import { Query } from "expo-sqlite";

const db = SQLite.openDatabase("interactive_systeme.db");

export const initDatabase = async () => {
    try {
        await db.transactionAsync(async (tx: SQLite.SQLTransactionAsync) => {
            await tx.executeSqlAsync(
                "CREATE TABLE IF NOT EXISTS category (guid VARCHAR(36) PRIMARY KEY, name TEXT, color TEXT, type TEXT);"
            );
            await tx.executeSqlAsync(
                "CREATE TABLE IF NOT EXISTS expense (guid VARCHAR(36) PRIMARY KEY, name TEXT, category_guid VARCHAR(36), datetime DATETIME, amount DOUBLE, FOREIGN KEY (category_guid) REFERENCES category(guid));"
            );
            console.log("Successfully initialized Tables!");
        });
    } catch (error) {

        console.log("Error initializing the Tables!");
        throw (error);
    }
};

export const addCategory = async (name: string, color: string, type: string) => {

    //needs user input validation for type and color (should be validated by this function)

    const UUID = uuid.v4();

    try {
        await db.transactionAsync(async (tx) => {
            await tx.executeSqlAsync("INSERT INTO category (guid, name, color, type) VALUES (?, ?, ?, ?);",
                [UUID.toString(), name, color, type]
            );
        });
        console.log("Category added successfully!");
    } catch (error) {
        console.log("Error adding category: ", error);
        throw error;
    }
}

export const addExpense = async (name: string, category_guid: string,datetime: string, amount: number) => {

    //needs user input validation for type and color (should be validated by this function)

    const expenseUUID = uuid.v4();

    try {
        await db.transactionAsync(async (tx) => {
            await tx.executeSqlAsync("INSERT INTO expense (guid, name, category_guid, datetime, amount) VALUES (?, ?, ?, ?, ?);", [expenseUUID.toString(), name, category_guid, datetime, amount]
            );
        });
        console.log("Expense added successfully!");
    } catch (error) {
        console.log("Error adding expense: ", error);
        throw error;
    }
};

export const deleteCategory = async (guid: string) => {
    try {
        await db.transactionAsync(async (tx: SQLite.SQLTransactionAsync) => {
            await tx.executeSqlAsync("DELETE FROM category WHERE guid = ?;", [guid]);
        }); 
    } catch(error) {
        console.log("Error deleting category: ", error);
        throw error;
    }
}

export const deleteExpense = async (guid: string) => {
    try {
        await db.transactionAsync(async (tx: SQLite.SQLTransactionAsync) => {
            await tx.executeSqlAsync("DELETE FROM expense WHERE guid = ?;", [guid]);
        }); 
    } catch(error) {
        console.log("Error deleting expense: ", error);
        throw error;
    }
}

export const executeQuery = async (query: string) => {
    const sqliteQuary: Query[] = [{sql: query, args: []}];    
    const result = await db.execAsync(sqliteQuary, true);
    return result;
}

export const deleteExpenses = async () => {
    try {
        await db.transactionAsync(async (tx: SQLite.SQLTransactionAsync) => {
            await tx.executeSqlAsync("DELETE FROM expense;");
        }); 
    } catch(error) {
        console.log("Error deleting expense: ", error);
        throw error;
    }
}

export const deleteDatabase = () => {
    closeDatabase().then(() => {
        try {
            db.deleteAsync()
        } catch (error) {
            console.log("Error deleting the Database: ", error);
            throw error;
        }

    });
    console.log("Database Deleted!")
}

const closeDatabase = async () => {
    try {
        db.closeAsync();
    } catch (error) {
        console.log("Error, cant close database: ", error);
        throw error;
    }
}
