const API_KEY = 'awoorwa32';

export const loadObject = async <T>(key: string, defaultObject: T): Promise<T> => {
    let localObject: Partial<T> = {};

    try {
        const json = localStorage.getItem(key);
        if (json) {
            localObject = JSON.parse(json);
        }
    } catch { }

    let remoteObject: Partial<T> = {};
    try {
        const response = await fetch(`https://demo.pabloader.ru/storage/${key}?_=${Math.random()}`);
        if (response.ok) {
            const compressedData = await response.blob();
            const decompressedData = await decompressBlob(compressedData);
            remoteObject = JSON.parse(await decompressedData.text());
        }
    } catch { }

    return { ...defaultObject, ...localObject, ...remoteObject };
}

export const saveObject = async <T>(key: string, obj: T) => {
    const saveData = JSON.stringify(obj);

    try {
        localStorage.setItem(key, saveData);
    } catch { }

    try {
        const url = new URL('https://demo.pabloader.ru/storage/index.php');
        url.searchParams.set('filename', key);

        const compressedData = await compressBlob(saveData);

        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/gzip',
                'Authorization': `Bearer ${API_KEY}`,
            },
            body: compressedData,
        });
        if (!response.ok) {
            throw new Error('Failed to save context');
        }
    } catch {
    }
}

export const compressBlob = async (blob: Blob | string): Promise<Blob> => {
    if (typeof blob === 'string') {
        blob = new Blob([blob]);
    }
    const cs = new CompressionStream("gzip");
    // @ts-ignore
    const compressedStream = blob.stream().pipeThrough(cs);
    return await new Response(compressedStream).blob();
}

export const decompressBlob = async (blob: Blob): Promise<Blob> => {
    const ds = new DecompressionStream("gzip");
    // @ts-ignore
    const decompressedStream = blob.stream().pipeThrough(ds);
    return await new Response(decompressedStream).blob();
}
