import { useFileStorage } from "@/app/hooks/useFileStorage";
import { useLogger } from "@/app/hooks/useLogger";
import { createContext, useEffect, useState } from "react";

export interface SettingsContextValue {
    getSetting: (key: string, def?: any) => any;
    setSetting: (key: string, value: any) => void;
}

export const SettingsProviderContext = createContext<SettingsContextValue|null>(null);

interface SettingsProviderProps {
    children?: React.ReactNode;
}

export function SettingsProvider(props: SettingsProviderProps) {
    const [settings, setSettings] = useState<any>({});
    const {readFile, writeFile} = useFileStorage();
    const log = useLogger('SettingsProvider');


    useEffect(() => {
        const loadSettings = async () => {
            const data = await readFile("settings.json");
            if(data){
                try {
                    const parsedSettings = JSON.parse(Buffer.from(data).toString());
                    setSettings(parsedSettings);
                } catch (e) {
                    log("Failed to parse settings.json");
                }
            }
        }
        loadSettings();
    }, []);

    const getSetting = (key: string, def? : any) => {
        if(settings[key] === undefined){
            return def;
        }
        return settings[key];
    }

    const setSetting = (key: string, value: any) => {
        setSettings((prevSettings: any) => {
            const newSettings = {...prevSettings, [key]: value};
            writeFile("settings.json", JSON.stringify(newSettings));
            return newSettings;
        });
    }

    return (
        <SettingsProviderContext.Provider value={{getSetting, setSetting}}>
            {props.children}
        </SettingsProviderContext.Provider>
    );
}