import { useDatabase } from "@/app/providers/DatabaseProvider/useDatabase";
import { createContext, useEffect } from "react";
import { useSystemAccount } from "./useSystemAccount";
import { usePublicKey } from "../AccountProvider/usePublicKey";
import { usePrivatePlain } from "../AccountProvider/usePrivatePlain";
import { APP_VERSION, RELEASE_NOTICE } from "@/app/version";
import { chacha20Encrypt, encodeWithPassword, encrypt } from "@/app/crypto/crypto";
import { generateRandomKey } from "@/app/utils/utils";
import { DeliveredMessageState } from "../DialogProvider/DialogProvider";
import { UserInformation } from "../InformationProvider/InformationProvider";
import { useNotification } from "@/app/hooks/useNotification";
import { useDialogsList } from "../DialogListProvider/useDialogsList";

export const SystemAccountContext = createContext(null);

export interface SystemUserInformation extends UserInformation {
    avatar: string;
}

interface SystemAccountProviderProps {
    children: React.ReactNode;
}

export function SystemAccountProvider(props : SystemAccountProviderProps) {
    const {runQuery} = useDatabase();
    const lastNoticeVersion = localStorage.getItem("lastNoticeVersion") || "0.0.0";
    const updateAccount = useSystemAccount("updates");
    const publicKey = usePublicKey();
    const privatePlain = usePrivatePlain();
    const {updateDialog} = useDialogsList();
    const notify = useNotification();

    useEffect(() => {
        if(publicKey == ""){
            return;
        }
        if(lastNoticeVersion !== APP_VERSION){
            sendReleaseNoticeFromUpdatesAccount();
            localStorage.setItem("lastNoticeVersion", APP_VERSION);
        }
    }, [lastNoticeVersion, publicKey]);

    const sendReleaseNoticeFromUpdatesAccount = async () => {
        const message = RELEASE_NOTICE;
        if(message.trim() == ""){
            return;
        }
        const cahchaEncrypted = await chacha20Encrypt(message.trim());
        const key = Buffer.concat([
            Buffer.from(cahchaEncrypted.key, "hex"),
            Buffer.from(cahchaEncrypted.nonce, "hex")]);
        const encryptedKey = await encrypt(key.toString('binary'), publicKey);
        const messageId = generateRandomKey(16);
        const plainMessage = await encodeWithPassword(privatePlain, message.trim());



        await runQuery(`
            INSERT INTO messages 
                (from_public_key, to_public_key, content, timestamp, read, chacha_key, from_me, plain_message, account, message_id, delivered, attachments) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            `, [updateAccount!.publicKey, publicKey, cahchaEncrypted.ciphertext, Date.now(), 0, encryptedKey, 0, plainMessage, publicKey, messageId, DeliveredMessageState.DELIVERED, JSON.stringify([])]);
        updateDialog(updateAccount!.publicKey);
        notify("New message", "You have a new message");
    }


    return (
        <SystemAccountContext.Provider value={null}>
            {props.children}
        </SystemAccountContext.Provider>
    )
}