import path from 'path';
import { WORKING_DIR } from './constants';
import { promises as fs } from 'fs';
import sqlite3 from 'sqlite3'

let db : any = null;

export async function initializeDatabase(){
	await fs.mkdir(WORKING_DIR, { recursive: true });
	const dbPath = path.join(WORKING_DIR, 'r_d');
	const dbLink = new sqlite3.Database(dbPath);
	db = dbLink;
}

export function runQuery(query: string, params: any[] = []) : Promise<void> {
	return new Promise((resolve, reject) => {
		db.run(query, params, function (err) {
			if (err) {
				console.info("Query error: ", err, query, params);
				reject(err);
			} else {
				resolve();
			}
		});
	});
}

export function getQuery(query: string, params: any[] = []): Promise<any> {
	return new Promise((resolve, reject) => {
		db.get(query, params, (err, row) => {
			if (err) {
				reject(err);
			} else {
				resolve(row);
			}
		});
	});
}

export function allQuery(query: string, params: any[] = []): Promise<any[]> {
	return new Promise((resolve, reject) => {
		db.all(query, params, (err, rows) => {
			if (err) {
				reject(err);
			} else {
				resolve(rows);
			}
		});
	});
}

initializeDatabase();