import { useEffect, useState } from "react";
import { DialogRow } from "./DialogListProvider";
import { useDatabase } from "@/app/providers/DatabaseProvider/useDatabase";
import { usePublicKey } from "../AccountProvider/usePublicKey";
import { decodeWithPassword } from "@/app/workers/crypto/crypto";
import { constructLastMessageTextByAttachments } from "@/app/utils/constructLastMessageTextByAttachments";
import { usePrivatePlain } from "../AccountProvider/usePrivatePlain";
import { DeliveredMessageState, Message } from "../DialogProvider/DialogProvider";

/**
 * Получает информацию о последнем сообщении в диалоге и количестве непрочитанных сообщений,
 * работает как с групповыми диалогами, так и с личными.
 * Последнее сообщение содержит расшифрованный текст в поле plain_message.
 * @param row Диалог из списка диалогов
 * @returns информация о последнем сообщении и количестве непрочитанных сообщений
 */
export function useDialogInfo(row : DialogRow) : {
    lastMessage: Message;
    unreaded: number;
    loading: boolean;
} {
    const {getQuery} = useDatabase();
    const publicKey = usePublicKey();
    const privatePlain = usePrivatePlain();
    const [lastMessage, setLastMessage] = useState<Message>({
        from_public_key: '',
        to_public_key: '',
        content: '',
        timestamp: 0,
        chacha_key: '',
        readed: 0,
        from_me: 0,
        delivered: DeliveredMessageState.WAITING,
        message_id: '',
        plain_message: '',
        attachments: [],
    });
    const [unreaded, setUnreaded] = useState(0);    

    useEffect(() => {
        loadLastMessageInfo();
    }, [row.last_timestamp]);

    const loadLastMessageInfo = async () => {
        let message = await getQuery(`SELECT * FROM messages WHERE message_id = ? AND account = ? LIMIT 1`, [row.last_message_id, publicKey]);
        if(!message){
            return;
        }
        
        let lastMessage = '';
        try{
            lastMessage = await decodeWithPassword(privatePlain, message.plain_message);
        }catch(e){
            lastMessage = constructLastMessageTextByAttachments(message.attachments);
        }

        setLastMessage({
            ...message,
            plain_message: lastMessage,
            attachments: JSON.parse(message.attachments),
        });
        let unreadedCount = {
            count: 0
        };
        if(row.dialog_id.startsWith('#group:')){
            unreadedCount = await getQuery(`
                SELECT COUNT(*) as count 
                FROM messages 
                WHERE read = 0 
                AND to_public_key = ?
                AND account = ?`, [row.dialog_id, publicKey]);
        }else{
            unreadedCount = await getQuery(`
                SELECT COUNT(*) as count 
                FROM messages 
                WHERE read = 0 
                AND ((from_public_key = ? AND to_public_key = ?) OR (from_public_key = ? AND to_public_key = ?))
                AND account = ?`, [publicKey, row.dialog_id, row.dialog_id, publicKey, publicKey]);
        }
        setUnreaded(unreadedCount.count);
    }    

    return {
        lastMessage,
        unreaded,
        loading: lastMessage.message_id == '',
    }
}