export type DrawCallback = (
	ctx: CanvasRenderingContext2D,
	time: number,
) => void;
export type InitDrawCallback = (
	ctx: CanvasRenderingContext2D,
	time: number,
	canvas: HTMLCanvasElement,
) => void;

class Screen {
	private readonly canvasEl: HTMLCanvasElement;
	private readonly ctx: CanvasRenderingContext2D;

	constructor(selector: string = 'canvas') {
		this.canvasEl = document.querySelector(selector) as HTMLCanvasElement;

		if (!this.canvasEl) {
			throw new Error('no element on the page');
		}

		this.ctx = this.canvasEl.getContext('2d') as CanvasRenderingContext2D;
	}

	clear() {
		this.ctx.clearRect(0, 0, 128, 128);
	}

	draw(drawCallback: DrawCallback, initCallback?: InitDrawCallback) {
		let currentTime = 0;

		const drawFrame = (time: number) => {
			currentTime = time;
			this.clear();
			drawCallback(this.ctx, currentTime);
			requestAnimationFrame(drawFrame);
		};

		requestAnimationFrame((time) => {
			currentTime = time;
			if (initCallback) {
				initCallback(this.ctx, currentTime, this.canvasEl);
			}
			drawFrame(currentTime);
		});
	}
}

export default Screen;
