import {FileMetas, FileType} from "./model.ts";

export const toBoolean = (value: boolean | "true" | "false"): boolean => {
    return value === "true" ? true : (value === "false" ? false : value);
};

export const createFrame = (url?: string | undefined | null): HTMLIFrameElement => {
    const frame = document.createElement('iframe');
    frame.name = 'cloud-file-player-iframe';
    frame.setAttribute('style', 'position:absolute;top:0;left:0;width:100%;height:100%;border:0');
    if (url) {
        frame.src = url;
    }
    return  frame;
}

export const jsonp = <T>(url: string, timeout: number = 30000): Promise<T> => {
    return new Promise((resolve, reject) => {
        const name = `jsonp_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
        const script = document.createElement('script');
        let timer: number | undefined;

        const cleanup = () => {
            if (script.parentNode) {
                script.parentNode.removeChild(script);
            }
            delete (window as any)[name];
            if (timer) {
                clearTimeout(timer);
            }
        };

        (window as any)[name] = (data: T) => {
            resolve(data);
            cleanup();
        };

        script.onerror = () => {
            reject(new Error(`JSONP request to ${url} failed`));
            cleanup();
        };

        if (timeout) {
            timer = window.setTimeout(() => {
                reject(new Error(`JSONP request to ${url} timed out`));
                cleanup();
            }, timeout);
        }

        const separator = url.includes('?') ? '&' : '?';
        script.src = `${url}${separator}callback=${name}`;
        document.head.appendChild(script);
    });
};

export const fetchFileMetas = async (url: string): Promise<FileMetas> => {
    return new Promise(async (resolve, reject) => {
        const resp: any = await jsonp(url);
        if (!resp) {
            reject(new Error(`Failed to fetch file metas from ${url}`));
            return ;
        }

        const html = resp.args.html;
        if (html && html.key) {
            html.url = html.key;
            delete html.key;
        }

        const fileMetas = {
            id: resp.args.resource.no,
            name: resp.args.resource.name,
            type: resp.type as FileType,
            page: parseInt(resp.args.resource.length),
            thumb: resp.args.resource.thumbnail,
            html: html,
            image: resp.args.image,
            animation: resp.args.animation,
        } as FileMetas;

        resolve(fileMetas);
    });
}