/**
 * @(#)FirstMoveStrategy.java	11/03/05
 * 
 * Copyright 2005 3GP01, KCL.  All unmodified code is copyright of its respective owner.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * The GNU General Public Licence should be contained within licence.txt;
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA  02110-1301, USA.
 */

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * This class contains methods to generate a computer player's first move.
 * Removed some clutter, used methods virtually untouched.
 * 
 * @author 3GP01 - Hardev Bhamra, Deepak Chandarana, James Tompkin
 * @version 1.0
 * @see MoveStrategy
 */

public class FirstMoveStrategy extends MoveStrategy 
{
	public Move generateMove(Game g) 
	{
		Board b = g.getBoard();
		Rack r = g.getRack();
		int rsize = r.getRackSize();
		List letters = new ArrayList();
		for (int i = 0; i < rsize; i++) 
		{
			letters.add("" + r.getLetter(i).toAscii());
		}
		letters.add(null); // dummy
		SublistIterator si = new SublistIterator(letters);

		int maxscore = 0;
		Word maxword = null;

		do {
			ArrayList curr = (ArrayList) si.getCurrent();
			//System.out.println(curr);
			int x = curr.size(); // only interested if x > 2

			ArrayList cc = (ArrayList) curr.clone();
			cc.remove(x - 1);
			Set possible = Dictionary.lookup(cc, x - 1); // perms of cc

			//System.out.println(possible); 
			Iterator j = possible.iterator();
			while (j.hasNext()) 
			{
				String wd = (String) j.next(); // it has length x-1

				ArrayList cc1 = (ArrayList) cc.clone();
				String wd2 = isValid(wd, cc1);
				if (wd2 != null) 
				{
					Word word = new Word(7, 7, 7 + x - 2, 7, wd2);
					int score = word.getScore(b);
					if (score > maxscore) 
					{
						maxscore = score;
						maxword = word;
					}
				}
			}
			si.advance();
		} while (!si.atEnd());

		if (maxword != null) 
		{
			Move mv = new Move(g.getPlayer(), maxword, b);
			return mv;
		}
		return null;
	}

	public static void main(String[] args) 
	{
		String wd = "idealiie";
		ArrayList cc = new ArrayList();
		cc.add("i");
		cc.add("d");
		cc.add("i");
		cc.add("i");
		cc.add("e");
		cc.add("a");
		cc.add("e");
		cc.add("l");
		FirstMoveStrategy fms = new FirstMoveStrategy();
		System.out.println(fms.checkValid(wd, cc));
	}

}