import { useMemory } from "../MemoryProvider/useMemory";
import { Message } from "./DialogProvider";

export interface DialogCache {
    publicKey: string;
    messages: Message[];
}

export function useDialogsCache() {
    const [dialogsCache, setDialogsCache] = useMemory<DialogCache[]>("dialogs-cache", [], true);
    
    const getDialogCache = (publicKey: string) => {
        const found = dialogsCache.find((cache) => cache.publicKey == publicKey);
        if(!found){
            return [];
        }
        return found.messages;
    }

    const addOrUpdateDialogCache = (publicKey: string, messages: Message[]) => {
        const existingIndex = dialogsCache.findIndex((cache) => cache.publicKey == publicKey);
        let newCache = [...dialogsCache];
        if(existingIndex !== -1){
            newCache[existingIndex].messages = messages;
        }else{
            newCache.push({publicKey, messages});
        }
        setDialogsCache(newCache);
    }

    const updateAttachmentInDialogCache = (attachment_id: string, blob: string) => {
        /**
         * TODO: Оптимизировать чтобы проходил снизу вверх
         */
        let newCache = dialogsCache.map((cache) => {
            let newMessages = cache.messages.map((message) => {
                if(message.attachments){
                    let newAttachments = message.attachments.map((attachment) => {
                        if(attachment.id == attachment_id){
                            return {
                                ...attachment,
                                blob: blob
                            }
                        }
                        return attachment;
                    });
                    return {
                        ...message,
                        attachments: newAttachments
                    }
                }
                return message;
            });
            return {
                ...cache,
                messages: newMessages
            }
        });
        setDialogsCache(newCache);
    }

    return {
        getDialogCache,
        addOrUpdateDialogCache,
        dialogsCache,
        updateAttachmentInDialogCache,
        setDialogsCache
    }
}