import { Parser } from 'svga';

const loadCache = {}

class ParserPoll {

    max: number = 3;

    poll: Parser[] = [];

    constructor(max: number = 3) {
        this.max = max;
    }

    get length(): number {
        return this.poll.length;
    }

    get() {
        return this.poll.pop() || new Parser();
    }

    put(parser: Parser) {
        if (this.length + 1 > this.max) {
            parser.destroy();
            return;
        }
        this.poll.push(parser);
    }

}

const parserPoll = new ParserPoll(3);

export const loadSvga = async (src: string) => {
    if (!loadCache[src]) {
        loadCache[src] = new Promise(async (resolve) => {
            const parser = parserPoll.get();
            // const parser = new Parser();
            const svga = await parser.load(src);
            parserPoll.put(parser);
            // parser.destroy();
            resolve(svga);
        });
    }

    return await loadCache[src];
}

export const loadSvgaList = async (srcList: string[]) => {
    const ps = srcList.map((src) => {
        return loadSvga(src)
    });

    return await Promise.all(ps);
}


export function loadImage(src: string): Promise<HTMLImageElement> {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = 'anonymous';
        img.onload = function () {
            resolve(img);
        };
        img.onerror = function (e) {
            reject(e);
        };
        img.src = src;
    });
}