import { useContext } from "react";
import { useMemory } from "../MemoryProvider/useMemory";
import { Attachment } from "../ProtocolProvider/protocol/packets/packet.message";
import { DialogContext } from "./DialogProvider";

export interface Reply {
    publicKey: string;
    messages: MessageReply[];
    /**
     * Флаг, указывающи, что выбранные сообщения уже перемещены в 
     * поле ввода диалога
     */
    inDialogInput?: string;
}

export interface MessageReply {
    timestamp: number;
    publicKey: string;
    message: string;
    attachments: Attachment[];
    message_id: string;
    chacha_key_plain: string;
}

export function useReplyMessages() {
    const [replyMessages, setReplyMessages] = useMemory<Reply>("replyMessages", {
        publicKey: "",
        messages: [],
        inDialogInput: ""
    }, true);
    const context = useContext(DialogContext);
    if(!context){
        throw new Error("useReplyMessages must be used within a DialogProvider");
    }

    const {dialog} = context;

    const selectMessage = (message : MessageReply) => {
        if(replyMessages.publicKey != dialog){
            /**
             * Сброс выбора сообщений из другого диалога
             */
            setReplyMessages({
                publicKey: dialog,
                messages: [message]
            });
            return;
        }
        if(replyMessages.messages.find(m => m.timestamp == message.timestamp)){
            /**
             * Уже выбранное сообщение
             */
            return;
        }
        replyMessages.messages.push(message);
        const sortedByTime = replyMessages.messages.sort((a, b) => a.timestamp - b.timestamp);
        setReplyMessages({
            publicKey: dialog,
            messages: sortedByTime
        });
    }

    const deselectMessage = (message : MessageReply) => {
        const filtered = replyMessages.messages.filter(m => m.timestamp != message.timestamp);
        setReplyMessages({
            publicKey: dialog,
            messages: filtered
        });
    }

    const deselectAllMessages = () => {
        setReplyMessages({
            publicKey: "",
            messages: []
        });
    }

    const isSelectionStarted = () => {
        if(replyMessages.inDialogInput){
            return false;
        }
        return replyMessages.publicKey == dialog && replyMessages.messages.length > 0;
    }

    const isSelectionInCurrentDialog = () => {
        if(replyMessages.inDialogInput){
            return false;
        }
        return replyMessages.publicKey == dialog;
    }

    const isMessageSelected = (message : MessageReply) => {
        if(replyMessages.publicKey != dialog ||
            replyMessages.inDialogInput
        ){
            return false;
        }
        return replyMessages.messages.find(m => m.timestamp == message.timestamp) != undefined;
    }

    const translateMessagesToDialogInput = (publicKey: string) => {
        setReplyMessages((prev) => ({
            ...prev,
            inDialogInput: publicKey
        }));
    }

    return {replyMessages, 
            translateMessagesToDialogInput, 
            isSelectionInCurrentDialog, 
            isSelectionStarted, 
            selectMessage, 
            deselectMessage, 
            dialog,
            deselectAllMessages, 
            isMessageSelected}
}