import { QWebChannel } from '@/utils/qt/qwebchannel.js';

declare global {
    interface Window {
        qt: {
            webChannelTransport: {
                send: (payload: any) => void;
                onmessage: (payload: any) => void;
            };
        };
    }
}

function base64ToUint8Array(base64String: string) {
    const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
    const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/');

    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
}
export function qtAction() {
    // 获取 与qt交互实例
    let qtWebChannel: any = null;
    const webChannelTransport = window.qt?.webChannelTransport;
    if (webChannelTransport) {
        new QWebChannel(webChannelTransport, (channel: any) => {
            // all published objects are available in channel.objects under
            // the identifier set in their attached WebChannel.id property
            qtWebChannel = channel.objects.bridge;
            console.log('qtWebChannel', qtWebChannel);
        });
    }

    function getQtInfo(): Promise<Uint8Array[]> {
        if (qtWebChannel) {
            return qtWebChannel.getSystemInfo().then((res: any) => {
                return base64ToUint8Array(res);
            });
        } else {
            console.warn('qtWebChannel is null');
            return Promise.resolve([]);
        }
    }
    return { getQtInfo };
}

