/*
  crossword -- a crossword game
  Copyright (C) 2000 Falk Hueffner

  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.
  
  You should have received a copy of the GNU General Public License along with
  this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  Place, Suite 330, Boston, MA 02111-1307 USA

  $Id: HumanPlayer.cc,v 1.5 2000/11/28 23:41:47 falk Exp $
*/

//#include <ctype.h>
#include <ctype.h>
#include <stdlib.h>

#include <vector>

#include "HumanPlayer.hh"

void HumanPlayer::apply(const Move& move) {
    board.apply(move);
}

Move HumanPlayer::getMove() {
    Move move;

    do {
	cout << board
	     << "Your letters: " << letters << endl;

	int x, y;
	Pos pos = -1;
	do {
	    cout << "Where do you want to place your move? ";
	    string where;
	    cin >> where;
	    if (where.length() < 2)
		continue;
	    x = toupper(where[0]) - 'A';
	    y = atoi(where.substr(1).c_str()) - 1;
	    pos = x + y * Rules::xsize();
	    cout << PPos(pos) << " "  << where.substr(1) << endl;
	} while (pos < 0 || pos >= Rules::numFields());

	char d;
	do {
	    cout << "right (r) or down (d)? ";
	    cin >> d;
	    d = toupper(d);
	} while (d != 'R' && d != 'D');

	Dir dir;
	int border;
	if (d == 'R') {
	    dir = Rules::right();
	    border = (y + 1) * Rules::xsize();
	} else {
	    dir = Rules::down();
	    border = Rules::numFields();
	}

	cout << "Please enter the word: ";
	string word;
	cin >> word;

	Pos p = pos;
	std::string tmpLetters = letters;
	for (int i = 0; i < word.length(); ++i) {
	    word[i] = toupper(word[i]);
	    if (board.empty(p)) {
		std::string::size_type pl = tmpLetters.find(word[i]);
		if (pl == std::string::npos)
		    pl = tmpLetters.find('*');
		if (pl == std::string::npos) {
		    cout << "You don't have a " << word[i] << "!\n";
		    move.clear();
		    break;		    
		}
		tmpLetters.erase(pl, 1);

		move.push_back(Put(p, word[i]));
	    } else {
		if (board.at(p) != word[i]) {
		    cout << word[i] << " doesn't fit at " << PPos(p)
			 << ", there's a " << board.at(p) << "!\n";
		    move.clear();
		    break;
		}
	    }
	    p += dir;
	    if (p > border) {
		cout << "Too long!\n";
		move.clear();
		break;
	    }
	}
    } while (move.empty());

    return move;
}

