class Scrambler {
	
	def SpellChecker spellChecker
	
	def scramble(word) {
		Random rand = new Random()
		def result = (word.length()..1).inject(["", word]) { carry, index ->
			def randomNumber = rand.nextInt(index)
			def buildString = carry[0]
			def stripString = carry[1]
			def letter = stripString[randomNumber]
		  [buildString << letter, stripString - letter]
		}
		result[0]
	}
	
	def score(scrambled, guess) {
		if(guess.length() > scrambled.length())
		  throw new RuntimeException("Too many letters")
		
		if(guess.find { !scrambled.contains(it) } || !correctSpelling(guess))
		  0
	  else
		  computeScore(guess) + scoreForBonus(scrambled, guess)
	}
	
	def computeScore(guess) {
		guess.inject (0) { score, letter ->
			score + scoreForLetter(letter.toUpperCase())
		}
	}
	
	def scoreForLetter(letter) {
		def letterScores = [
		A : 1, C : 1, D : 1, E : 1, I : 1, N : 1, O : 1, R : 1, S : 1, T : 1,
		G : 2, H : 2, L : 2,
		K : 3, W : 3, X : 3,
		M : 4, U : 4, Y : 4,
		P : 5, V : 5, Z : 5,
		B : 8, F : 8, Q : 8,
		J : 10
		]
		
		letterScores.get(letter)
	}
	
	def scoreForBonus(scrambled, guess) {
		scrambled.toCharArray().toList().sort() == guess.toCharArray().toList().sort() ? 10 : 0
	}
	
	def correctSpelling(word) {
		spellChecker.checkSpelling(word)
	}
}