import { assertExists } from "https://deno.land/std@0.224.0/assert/assert_exists.ts";

import { Awaitable } from "../utils.ts";
import { Gaming, GuessResult, Info } from "./game.ts";

export class ManualProxy implements Gaming {
	word_length;

	constructor(length: number) {
		this.word_length = length;
	}

	guess(guess: string): Awaitable<GuessResult> {
		console.log("<proxy> Guessing:", guess);
		const result = read_until_correct(this.word_length);
		console.log();
		return result;
	}

	length(): number {
		return this.word_length;
	}
}

function read_until_correct(length: number): GuessResult {
	while (true) {
		const input = prompt("<proxy>   Result:");
		assertExists(input);
		const informations = parse_input(input, length);
		if (informations === null) {
			console.log("<proxy> incorrect input, try again");
			continue;
		}
		if (informations.every((i) => i.kind === "there")) return { kind: "success" };
		return { kind: "failure", informations };
	}
}

function parse_input(input: string, length: number) {
	const parsed = [] as Info[];
	for (const character of input.trim()) {
		if (character === ".") parsed.push({ kind: "abscent" });
		if (character === "-") parsed.push({ kind: "somewhere" });
		if (character === "+") parsed.push({ kind: "there" });
	}
	if (parsed.length !== length) return null;
	else return parsed;
}
