import { getDatabaseService } from './database.service.js';
import { encryptDataWithUserKey, decryptDataWithUserKey, hashElement } from './encryption.js';
import type { Database } from 'node-sqlite3-wasm';
import crypto from 'crypto';

export default class System {
    public static getDb(): Database {
        const db: Database | null = getDatabaseService().getDb();
        if (!db) {
            throw new Error('Database not initialized');
        }
        return db;
    }
    
    public static encryptDataWithUserKey(data: string, userKey: string): string {
        return encryptDataWithUserKey(data, userKey);
    }
    
    public static timeStampInSeconds(): number {
        const date:number = new Date().getTime();
        return Math.floor(date / 1000);
    }
    
    public static decryptDataWithUserKey(encryptedData: string, userKey: string): string {
        return decryptDataWithUserKey(encryptedData, userKey);
    }
    
    public static createUniqueId(): string {
        return crypto.randomUUID();
    }
    
    static htmlToText(htmlNode: string): string {
        let text: string = htmlNode
            .replace(/<\/?p[^>]*>/gi, '\n')
            .replace(/<br\s*\/?>/gi, '\n')
            .replace(/<\/?(span|h[1-6])[^>]*>/gi, '');
        text = text
            .replace(/&apos;/g, "'")
            .replace(/&quot;/g, '"')
            .replace(/&amp;/g, '&')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&#39;/g, "'");
        text = text.replace(/\r?\n\s*\n/g, '\n');
        text = text.replace(/[ \t]+/g, ' ');
        
        return text.trim();
    }
    
    public static getCurrentDate(): string {
        return new Date().toISOString();
    }
    
    static dateToMySqlDate(isoDateString: string): string {
        const dateObject: Date = new Date(isoDateString);
        
        function padWithZeroes(value: number): string {
            return value.toString().padStart(2, '0');
        }
        
        const year: number = dateObject.getFullYear();
        const month: string = padWithZeroes(dateObject.getMonth() + 1);
        const day: string = padWithZeroes(dateObject.getDate());
        
        return `${year}-${month}-${day}`;
    }
    
    public static hashElement(element: string): string {
        return hashElement(element);
    }
}