import {decode_pixel_frame, pack_pixel_rows, type Pixel_Frame} from "../protocol/pixel_frame";
export class Pixel_Presenter {
    private latest_frame: Pixel_Frame | null = null; private canvas: HTMLCanvasElement | null = null; private context: CanvasRenderingContext2D | null = null;
    attach(canvas: HTMLCanvasElement): void {this.canvas=canvas; this.context=canvas.getContext("2d",{alpha:false});}
    detach(): void {this.canvas=null;this.context=null;this.latest_frame=null;}
    accept(buffer: ArrayBuffer): {signature: number; overwritten: boolean} {const frame=decode_pixel_frame(buffer); let hash=(2166136261^frame.width^(frame.height<<16))>>>0; const count=Math.min(4096,frame.pixels.length); for(let index=0;index<count;index++){const offset=count<=1?0:Math.floor(index*(frame.pixels.length-1)/(count-1));hash=Math.imul(hash^frame.pixels[offset],16777619)>>>0;} const overwritten=this.latest_frame!==null;this.latest_frame=frame;return {signature:hash,overwritten};}
    present(): boolean {const frame=this.latest_frame, canvas=this.canvas, context=this.context;if(!frame||!canvas||!context)return false;this.latest_frame=null;if(canvas.width!==frame.width||canvas.height!==frame.height){canvas.width=frame.width;canvas.height=frame.height;}const pixels=new Uint8ClampedArray(frame.width*frame.height*4);pixels.set(pack_pixel_rows(frame));context.putImageData(new ImageData(pixels,frame.width,frame.height),0,0);return true;}
}
