export class RawImageData {
    height: number;
    width: number;
    pixels: ArrayBuffer;
    private _objectUrl: string | null = null;

    constructor(buff: ArrayBuffer) {
        const view = new DataView(buff);
        this.width = view.getUint32(0, true); // true for little-endian
        this.height = view.getUint32(4, true);
        this.pixels = buff.slice(8);
    }

    private createImageData(): ImageData {
        const uint8Array = new Uint8Array(this.pixels);
        return new ImageData(
            new Uint8ClampedArray(uint8Array),
            this.width,
            this.height
            ,
        );
    }

    toObjectUrl(): string {
        if (this._objectUrl) {
            return this._objectUrl;
        }

        const canvas = document.createElement('canvas');
        canvas.width = this.width;
        canvas.height = this.height;

        const ctx = canvas.getContext('2d');
        if (!ctx) {
            throw new Error('Could not get canvas context');
        }

        const imageData = this.createImageData();
        ctx.putImageData(imageData, 0, 0);

        this._objectUrl = canvas.toDataURL('image/png');
        return this._objectUrl;
    }

    dispose() {
        if (this._objectUrl) {
            URL.revokeObjectURL(this._objectUrl);
            this._objectUrl = null;
        }
    }
}