package como.commlet.webcheckers;

import java.awt.*;
import java.applet.*;
import java.applet.AudioClip;
import java.io.*;
import java.util.*;

import como.sys.*;
import como.util.*;
import como.awt.*;
import como.commlet.*;
import como.io.*;
import como.commlet.superchat.*;
import como.commlet.userlist.*;

public class WebCheckers extends MetaCommlet {

  //MEMBRES
private Image background = null;

public Damier damier = null;
private Label The_Label;
private Label Name1,Name2;
private Button NewGame;
private SmartFrame NotYourTurnFrame = null;
private Move The_Move;


public Joueur Player1, Player2;

public static int MSG_NEW_GAME = 10100; 
public static int MSG_MOVE     = 10101; 
public static int MSG_TURN     = 10102; 
public static int MSG_DEUCE    = 10103; 

private int oponnentID;
private boolean myturn;
private boolean wasmyturn;
private int myID;
private MenuItem monmenuquit;

private AudioClip sounds[];

  //CONSTRUCTEUR

public WebCheckers(){

}

  //METHODES

public void loadSounds(){ // chargement des sons...
  sounds = new AudioClip[7];
  sounds[0] = com.loadAudioClip("hi.au");
  sounds[1] = com.loadAudioClip("laugh.au");
  sounds[2] = com.loadAudioClip("what.au");
  sounds[3] = com.loadAudioClip("thankyou.au");
  sounds[4] = com.loadAudioClip("no.au");
  sounds[5] = com.loadAudioClip("click.au");
  sounds[6] = com.loadAudioClip("yeah.au");
}

public String getCommletName(){
  return "WebCheckers";
}

public String getCommletInfo(){
  return "WebCheckers Version 1.0";
}

public void init(){

  super.init();

  // pour demontrer les posibilites de la classe MetaCommlet
  
  SuperChat c = new SuperChat();
  addCommlet(c,"SuperChat");   
  
  UserList ul = new UserList();
  addCommlet(ul,"Joueurs");

  Menu menfile = new Menu("File");
  monmenuquit = new MenuItem("Quit");
  
  menfile.add(monmenuquit);

  getMenuBar().add(menfile);

  myinit();
  resize(650,700);
}

public void start(){
  myinit();
}

public void stop(){
  com.logout();
  super.stop();
}

public void addUser(int who)
{
  // recuperation des noms et ID des joueurs

  Vector users = com.getUsers();
  if (users.size() != 2) // 2 utilisateurs seulement
    return;

  Enumeration e = users.elements();
  int[] ids = new int[2];
  int i = 0;
  while (e.hasMoreElements() && (i <2)) {
    User u = (User)e.nextElement();
    ids[i] = u.getID();
    i++;
  }

  myID=com.getMyID();
  
  // recuperation de l'ID de l'opposant

  if (ids[0]==myID)  // theoriquement en 0 ou 1
    oponnentID=ids[1];
  else
    oponnentID=ids[0]; 

  if (com.iAmMaster()) // je jouerai donc en premier donc en UP
    {
      Player1 = new Joueur(Joueur.UP,com.getUserName(myID));
      Player2 = new Joueur(Joueur.DOWN,com.getUserName(oponnentID));
      myturn=true;
      wasmyturn=false;
    }
  else
    {
      Player1 = new Joueur(Joueur.UP,com.getUserName(oponnentID));
      Player2 = new Joueur(Joueur.DOWN,com.getUserName(myID));
      myturn=false;
      wasmyturn=false;
    }
  ResetGame();

}

private void myinit(){

  // numero de version

  System.out.println("NetDames Network Version 1.0f");
 
  // ResetGame();

}

public void ResetGame () {

  repaint();

  if (damier == null){
    Name1 = new Label(Player1.Name,Label.CENTER);
    Name2 = new Label(Player2.Name,Label.CENTER);
    NewGame = new Button("New game");
    The_Label = new Label("               C'est aux "+Player1.Get_Color_String()
			  +"s de jouer.               ",Label.CENTER);
    loadSounds();
  }

  if (!com.iAmMaster())
    {
    // seul le maitre du ComObj peut relancer une partie

    NewGame.disable();
    wasmyturn=false;
    myturn=false;
    }
  else
    {
      wasmyturn=false;
      myturn=true;
    }

  if (damier != null){
    damier.Restart();
    sounds[0].play();
    return;
  }

  damier = new Damier(Player1,Player2,The_Label);
  damier.SetSounds(sounds,7);

  removeAll();
  GridBagLayout My_Layout = new GridBagLayout();
  setLayout(My_Layout);
  GridBagConstraints Constraints = new GridBagConstraints ();
  Constraints.insets = new Insets(10,10,10,10);
  Constraints.anchor = GridBagConstraints.CENTER;
  Constraints.fill = GridBagConstraints.NONE;
  Constraints.gridwidth = GridBagConstraints.REMAINDER;
  My_Layout.setConstraints(NewGame,Constraints);
  add(NewGame);
  My_Layout.setConstraints(Name1,Constraints);
  add(Name1);
  My_Layout.setConstraints(damier,Constraints);
  add(damier);
  My_Layout.setConstraints(Name2,Constraints);
  add(Name2);
  My_Layout.setConstraints(The_Label,Constraints);
  add(The_Label);
  validate();
  sounds[0].play();
}


public boolean handleEvent (Event e) {
  int nbp = 0;
  
  // Quitter
  if (e.target == monmenuquit) {
    this.stop();
    return true;
  }

  // Recommencer une partie
  if ((e.target == NewGame) && (e.id == Event.ACTION_EVENT) && com.iAmMaster()){
    ResetGame();

    // transmission de la nouvelle partie a l'opposant
    Msg mess=new Msg(MSG_NEW_GAME);
    mess.to=oponnentID;
    com.sendTo(mess);
    return true;
  }
  if ((e.id == Event.ACTION_EVENT) &&
      (((String)e.arg).equals(Case.CASE))){ // C'est une Case !

    if (myturn){ // est-ce mon tour ????
      if (damier.Source_Set()){
	if (damier.Set_Dest((Case)e.target)){
	  String movestr = damier.MoveStr();
	  The_Move = damier.Move();

	  // Ce que Como est cense pouvoir permettre : 
	  // L'envoi d'instances d'objets implementant l'interface Saveable
	  // Ne marche pas donc utilisation des String qui elles passent
	  // comme attribut de message

	  // transmission du deplacement
	  //	  Msg mess=new Msg(MSG_MOVE,The_Move);
	  //	  mess.to=oponnentID;
	  //	  com.sendTo(mess);

	  com.sendToOthers(new Msg(MSG_MOVE,movestr));
  
	  if (The_Move.Finished == 0){
	    sounds[6].play();
	    if (Player1.Loose()){
	      SmartFrame MSG = 
		new SmartFrame("Victoire des "+Player2.Get_Color_String()+"s !");
	      setText("Victoire des "+Player2.Get_Color_String()+"s !!");
	      MSG.show();
	    }
	    else{
	      SmartFrame MSG = 
		new SmartFrame("Victoire des "+Player1.Get_Color_String()+"s !!");
	      setText("Victoire des "+Player1.Get_Color_String()+"s !!");
	      MSG.show();
	    }
	  }

	  // faut il passer le tour ?

	  if (The_Move.Eating!=1)
	    {
	      // passer le tour
	      wasmyturn=true;
	      myturn=false;
	      Msg mess =new Msg(MSG_TURN);
	      //mess.to=oponnentID;
	      com.sendToOthers(mess);
	    }
	}
      }
      else 
	damier.Set_Source((Case)e.target);
    }
    else
    {
      //Rien ou Beep c'est pas son tour !!!
      if (NotYourTurnFrame == null)
	NotYourTurnFrame = new SmartFrame("Ce n'est pas votre tour !!!!");
      NotYourTurnFrame.show();
      sounds[4].play();
   }

    return true;
  }
  return super.handleEvent(e);
}

public void paint(Graphics g) {
  // chargement de l'image de fond.

  if (background == null) background = com.loadImage("or26.jpg");

  if (background != null){
    int i,j;
    Rectangle b = bounds();
    int w = b.width;
    int h = b.height;
    int wi = background.getWidth(this);
    int hi = background.getHeight(this);
    if (wi != -1 && hi != -1)
      for (i=0;i<w;i+=wi)
	for (j=0;j<h;j+=hi)
	  g.drawImage(background,i,j,this);
  }  

}
  

public void setText(String msg){
  The_Label.setText(msg);
}

public boolean isUserAdmitted(User who) {
  Vector users = com.getUsers();
  if (users.size() < 2) // 2 utilisateurs seulement
    return true;
  else
    return false;
}

public void userLeft(int RankWhoLeft) {
  // l'opposant a disparu -->
  // signaler

  SmartFrame UserLeftFrame = new SmartFrame("L'Opposant a disparu, partie abandonnee...");
  UserLeftFrame.show();
  // et arreter le jeu
  this.stop();
}

/**
* Handle an incoming message. This is called by the ComObj.
*/
public boolean handleMsg(Msg msg) {
        if (msg.type == Msg.NEW_USER_INFO) {
	  if (myID==msg.from)
	    return false;
	  
	  String newname = com.getUserName(msg.from);
	  if (com.iAmMaster())
	    // l'opposant est donc le Player2
	    {
	      Player2.Set_Name(newname);
	      Name2.setText(newname);
	    }
	   else
	    // l'opposant est donc le Player1
	    {
	      Player1.Set_Name(newname);
	      Name1.setText(newname);
	    }
	}
        if (msg.type == MSG_NEW_GAME) {
	  if (!com.iAmMaster())
		  ResetGame();
	}
	else if (msg.type == MSG_TURN) {
	  myturn = true; // temporaire
	  if (!wasmyturn)
	    myturn=true;
	  else 
	    wasmyturn=false;
	}
        if (msg.type == MSG_DEUCE) {
	  System.out.println("Match nul");
	  SmartFrame MSG = new SmartFrame("Match nul les gars!!");
	  MSG.show();
	  setText("Match nul!!");
	  sounds[1].play();
	}
	else if (msg.type == MSG_MOVE) {
	  if (!myturn){
	    damier.MakeMoveStr((String)msg.arg);
	    if (!damier.Can_I_Move())
	      // j'averti mon adversaire...
	      com.sendToAll(new Msg(MSG_DEUCE));
	  }
        }
  return super.handleMsg(msg);
}

}

