import { Memory } from "./Memory.js";

export class RenderPipeline {

	constructor(engine) {
		this.engine  = engine;
		this.device  = engine.device;

		this.blocks  = [];
		this.memory  = new Memory("pipeline");

		engine.addPipeline(this);
	}

	addBlock(block) {
		block.id       = this.blocks.length;
		block.pipeline = this;

		this.blocks.push(block);
		return block;
	}

	getBlock(id) {
		return this.blocks[id];
	}

	getBlockByName(name) {
	    return this.blocks.find(block => block.name === name) || null;
	}

	getPreviousBlock(block) {
		if (block.id === 0) return null;
		return this.blocks[block.id - 1];
	}

	async create() {
		for (const block of this.blocks) {
			for (const pass of block.getAllPasses()) {
				await pass.create();
			}
		}
	}

	async bindBuffers() {
		for (const block of this.blocks) {
			for (const pass of block.getAllPasses()) {
				await pass.bindBuffers();
			}
		}
	}

	async execute() {
		for (const block of this.blocks) {
			for (const pass of block.getAllPasses()) {
				await pass.execute();
				await this.device.queue.onSubmittedWorkDone();
			}
		}
	}

	async test() {
		for (const block of this.blocks) {
			for (const pass of block.getAllPasses()) {
				if (typeof pass.test === "function") {
					await pass.test();
				}
			}
		}
	}
}
