import { BaseEnumerator } from "./BaseEnumerator";
import { EnumeratorExecutor } from "./EnumeratorExecutor";
import { SingleEnumerator } from "./SingleEnumerator";

export class ParallelEnumerator extends BaseEnumerator {
	private _executors: EnumeratorExecutor[] = [];

	constructor(iterators: Iterator<any>[]) {
		super();
		if (iterators && iterators.length) {
			for (let iterator of iterators) {
				if (iterator instanceof BaseEnumerator) {
					this._executors.push(new EnumeratorExecutor(iterator, null));
				} else {
					this._executors.push(new EnumeratorExecutor(new SingleEnumerator(iterator), null));
				}
			}
		}
	}

	next(value?: any): IteratorResult<any> {
		if (this._executors.length) {
			// 先移除[doneFlag=true]協程
			let index = this._executors.length;
			while (index--) {
				let r = this._executors[index];
				if (r.doneFlag) {
					this._executors.splice(index, 1);
				}
			}

			if (this._executors.length == 0) {
				return { done: true, value: undefined };
			}

			// 執行協程
			for (let r of this._executors) {
				r.next(value);
			}

			return { done: false, value: undefined };
		}

		return { done: true, value: undefined };
	}
}
