/** (C) Game Page Network, Inc., Confidential, All Rights Reserved */
// MoveCommand.java
// --paul@gamepage.net, 31jul97

import java.util.*;

public class MoveCommand extends Command {
  MoveCommand() {
    super("move", -1, null,
	  "move TABLE NUMBER PIECE1 POS1 POS2 PIECE2 SECONDS [COMMENT].\n"+
	  "At TABLE, send game move NUMBER of PIECE1 from POS1 to POS2\n"+
	  "capturing (or promoting to) PIECE2. If no capture,\n"+
	  "PIECE2 should be the - character.\n"+
	  "SECONDS is current client calculation of seconds remaining.\n"+
          "  Uppercase pieces indicate lead (opening) team.\n"+
          "  Positions are letter (lead column left to right)"+
	  "and digit (row from lead), with a1 as front left corner.\n"+
          "  Syntax and error handling are game specific.\n"+
          "Example: move 5 1 P e4 e5 - 595 is a table 5 opening\n"+
	  "move of lead pawn from e5 with just under 10 minutes left.");
  }
  public void process(StringTokenizer args, Client c) {
    Member current = c.getMember();  

    if (args.countTokens()<7) {
      c.send("? move TABLE NUMBER PIECE1 POS1 POS2 PIECE2 SECONDS [NOTE]");
      return;
    }

    String name = args.nextToken();
    String command = args.nextToken("\0"); // for game.move()
    args = new StringTokenizer(command); // reset for use here
   
    Table table = Table.find(name);
    String error="! move "+name+": ";
    if (table==null) {
      c.send(error+"No such table.");
      return;
    }
    name = table.tag();
    if (!current.isPlayer(table)) {
      c.send(error+"You are not playing here.");
      return;
    }
    
    Game game = table.getGame();
    if (game==null || !game.hasPlayers()) {
      c.send(error+"No active game.");
      return;
    }
    if (!game.isActive()) {
      c.send(error+"Game has not started.");
      return;
    }
    if (!game.myTurn(current)) {
      c.send(error+"It is not your turn.");
      return;
    }
    
    StringBuffer buf = new StringBuffer(128);
    int moveResult = game.move(command,buf);
    if (moveResult==Club.SYN || moveResult==Club.ERR) {
      c.send(error+buf);
      return;
    }

    table.tell("move "+name+" "+command, Table.P1);
    // move @5 1 P e4 e5 - 1800 foo
    
    if (moveResult==Club.WIN) {
      Member opponent = table.getOpponent(current);
      table.record(current,'w',opponent);
    }
  }
}

