import { PNGReader } from "./png/PNGReader.js";

async function decode_png(png_bytes) {
    return new Promise((resolve, reject) => {

        const reader = new PNGReader(png_bytes);

        // console.time('decode');
        // console.profile('decode');

        const png = reader.parse();

        const uint_channels = png.getUint8Data();

        const width = png.getWidth();
        const height = png.getHeight();

        // console.timeEnd('decode');
        // console.profileEnd('decode');

        resolve({
            data: uint_channels.data.buffer,
            width,
            height,
            itemSize: uint_channels.itemSize,
            bitDepth: png.getBitDepth()
        });
    });
}

/**
 *
 * @param {ArrayBuffer} data
 * @param {string} type
 * @returns {Promise<unknown>}
 */
async function decode(data, type = 'png') {
    if (!(data instanceof ArrayBuffer)) {
        throw new Error('.data argument must be an ArrayBuffer, instead was something else');
    }

    const _type = type.toLowerCase();

    switch (_type) {
        case 'png':
            return await decode_png(data);
        default:

            throw new Error('Unsupported type');
    }

}

self.Lib = {
    decode
};
