package hangman;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class EvilHangman implements EvilHangmanGame {
	Set<String> startingSet = new TreeSet<String>();
	Map<String, Set<String>> partition = new TreeMap<String, Set<String>>();
	int length;
	String key;
	public EvilHangman(){
		length = 0;
		key = "";
	}
	public int getstartingSetsize(){
		return startingSet.size();
	}
	public String getWord(){
		return startingSet.iterator().next();
	}
	public void setLength(int length){
		this.length = length;
	}
	public String getKey(){
		return key;
	}
	public void startGame(File dictionary, int wordLength){
		try {
			startingSet.clear();
			setLength(wordLength);
			for(int i = 0; i < length; i++){
				key = key + "-";
			}
			Scanner scanner = new Scanner(dictionary);
			while(scanner.hasNext()){
				String word = scanner.next();
				if(word.length() == wordLength){
					startingSet.add(word);
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	public Set<String> makeGuess(char guess){
		partition.clear();
		for(String word: startingSet){
			String currentkey = keyGen(word,guess);
			if(partition.containsKey(currentkey)){
				partition.get(currentkey).add(word);
			}
			else{
				Set<String> newset = new TreeSet<String>();
				newset.add(word);
				partition.put(currentkey, newset);
			}
		}
		Set<String> curSet = new TreeSet<String>();
		curSet = getcurSet(guess);
		startingSet = curSet;
		return curSet;
	}
	public Set<String> getcurSet(char guess){
		String mostFrequentKey = getKey();
		Set<String> mostFrequentSet = new TreeSet<String>();
		for(Map.Entry<String, Set<String>> entry: partition.entrySet()){
			if(entry.getValue().size() > mostFrequentSet.size()){
				mostFrequentSet = entry.getValue();
				mostFrequentKey = entry.getKey();
			}
		}
		key = mostFrequentKey;
		return mostFrequentSet;
	}
	public String keyGen(String word, char guess){
		StringBuilder sb = new StringBuilder(length);
		for(int i = 0; i < length; i++){
			if(word.charAt(i) == guess){
				sb.append(guess);
			}
			else{
				sb.append(key.charAt(i));
			}
		}
		return sb.toString();
	}
}
