import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { OptionsComponent } from '../options/options.component';
import { SimMain } from './sim/SimMain';
import { GdRoot } from './data/GdRoot';
import { SimCommand } from './sim/commands/SimCommand';
import { VisMain } from './vis/VisMain';
import { SplashComponent } from '../splash/splash.component';

@Component({
	selector: 'app-game',
	templateUrl: './game.component.html',
	styleUrls: ['./game.component.css'],
	imports: [OptionsComponent],
})
export class GameComponent {
	simMain: SimMain = new SimMain();
	visMain!: VisMain;

	@ViewChild('gameCanvas') canvasRef!: ElementRef<HTMLCanvasElement>;
	@ViewChild('canvasWrapper') wrapperRef!: ElementRef<HTMLDivElement>;
	scaleX: number = 1;
	scaleY: number = 1;
	pixelScale: number = 1;
	optionsOpen: boolean = false;

	async ngAfterViewInit() {
		const gdRoot = await this.loadGdRoot();
		this.simMain.setGdRoot(gdRoot);
		this.visMain = new VisMain(this.simMain, SplashComponent.assetPreloader, this.wrapperRef.nativeElement, this.canvasRef.nativeElement);
		window.addEventListener('resize', _ => this.visMain.onResized());
	}

	start() {
		this.visMain.start();
	}

	stop() {
		this.visMain.start();
	}

	step() {
		this.simMain.step();
	}

	rewind() {
		//this.simMain.rewindToZero();
	}

	fastForward() {
		this.simMain.executeToEnd();
	}

	async loadGdRoot(): Promise<GdRoot> {
		const data = await fetch('/assets/data/gdRoot.json').then((r) =>
			r.json()
		);
		const gdRoot: GdRoot = data;
		return gdRoot;
	}

	async reloadGameData() {
		this.simMain.setGdRoot(await this.loadGdRoot());
	}

	// Called when opening options: pause the game
	public openOptions(): void {
		this.optionsOpen = true;
		this.stop();
	}

	// Called when closing options: resume the game
	public closeOptions(): void {
		this.optionsOpen = false;
		this.start();
	}
}
