import { CoroutineV2 } from "./CoroutineV2";

export default class CoroutineExample {
	private _obj: Object = { "a": true };
	private _obj2: Object = { "b": true };

	private _num: number = 3;

	/**
	 *
	 */
	constructor() {
		CoroutineV2.Single(this.Test1_1()).Start();
	}

	*Test1_1() {
		yield null;
		yield* this.Test1_2();
		// CoroutineV2.Single(this.Test1_3()).Start(this);
		yield this.Test1_3();
	}

	*Test1_2() {
		yield null;
	}

	*Test1_3() {
		yield this.Test1_3_1();
		yield CoroutineV2.Single(this.Test1_4()).Start(this._obj);
		// yield CoroutineV2.Single(this.Test1_4()); //.Start(this);
		// yield *this.Test1_4();
		console.log("main wait 3");
		yield CoroutineV2.WaitTime(2);
		console.log("done");
	}

	*Test1_3_1() {
		yield this.Test1_3_2();
		yield CoroutineV2.WaitTime(1);
		console.log("Test1_3_1.1");
		yield CoroutineV2.WaitTime(1);
		console.log("Test1_3_1.2");
	}

	*Test1_3_2() {
		yield this.Test1_3_3();
		yield CoroutineV2.WaitTime(1);
		console.log("Test1_3_2.1");
		yield CoroutineV2.WaitTime(1);
		console.log("Test1_3_2.2");
		yield CoroutineV2.WaitTime(1);
		console.log("Test1_3_2.3");
	}

	*Test1_3_3() {
		yield CoroutineV2.WaitTime(1);
		console.log("Test1_3_3.1");
		yield CoroutineV2.WaitTime(1);
		console.log("Test1_3_3.2");
		yield CoroutineV2.WaitTime(1);
		console.log("Test1_3_3.3");
	}

	*Test1_4() {
		this._num++;
		console.log(`WaitTime2 ${this._num}`);
		yield CoroutineV2.WaitTime(2).Start(this._obj2);
		this._num++;
		console.log(`WaitTime2 ${this._num}`);
		yield CoroutineV2.WaitTime(2).Start(this._obj2);
		this._num++;
		console.log(`WaitTime2 ${this._num}`);
	}

	*Test2_1() {
		console.log("111");
		CoroutineV2.Single(this.Test2_2()).Start(this);
		console.log("333");
	}

	*Test2_2() {
		console.log("222");
		return;
	}

	*Coroutine1(start: number, end: number) {
		for (let i = start; i <= end; i++) {
			// yield CoroutineV2.WaitTime(1).Start(); // Start()可以省略, 會由外層啟動
			// yield CoroutineV2.WaitTime(1).Start(this); // target也可以省略, 由外層的target控制

			yield CoroutineV2.WaitTime(1).Start();
			console.log(`C1 => ${i}`);

			// 嵌套
			yield CoroutineV2
				.WaitTime(1)
				.ThenParallel(
					// 再嵌套
					CoroutineV2.Action(() => console.log("start parallel")),
					this.Coroutine2(10, 2),
					this.Coroutine2(20, 2),
				)
				.ThenAction(() => console.log("end parallel"))
				.Start();

			// Promise
			yield this.loadItemAsync("settings.json");
		}
	}

	*Coroutine2(num: number, repeat: number) {
		for (let i = 0; i < repeat; i++) {
			//yield CoroutineV2.WaitTime(2);
			yield 0;
			console.log(`C2: ${num}`);
			// yield CoroutineV2.WaitTime(1);
		}
	}

	actionCallback() {
		console.log("action callback 2");
	}

	loadItemAsync(id: string): Promise<{ id: string }> {
		return new Promise((resolve) => {
			console.log("loading item start:", id);
			setTimeout(() => {
				resolve({ id: id });
				console.log("loading item done:", id);
			}, 3000);
		});
	}
}
