
import nim.*;
import nimtool.*;
import nimclient.*;
import nimgui.*;

import java.util.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;


public class ClientTest {


  private static class NimReferee  extends Thread {
  
    private final RemoteNimGame game;
    private final NimUser user;
    
    NimReferee( RemoteNimGame game, NimUser user ) {
    
      this.game = game;
      this.user = user;
    }
    
    public void run() {
    
      user.outcome( game.wins(), game.loses() );
    }
  }


  private static class Monitor  implements Observer {
  
    public void update( Observable obs, Object obj ) {
    
      System.out.println( obj );
    }
  }


  // Disposizione delle compontenti e avvio del client
  
  private static void setUp( Image matchImg, Container pane ) {
  
    pane.prepareImage( matchImg, pane );
    
    NimView user = new NimView( matchImg );
    
    pane.setLayout( new BorderLayout() );
    pane.add( BorderLayout.CENTER, user );
    
    try {
    
      NimClient client = new NimClient( "localhost" );
      RemoteNimGame game = client.getGameProxy();
      
      game.addObserver( new Monitor() );
      
      runGame( game, user );
    
    } catch ( IOException ioe ) {
    
      ioe.printStackTrace();
    }
  }
  
  
  // Configurazione e avvio del gioco
  
  private static void runGame( RemoteNimGame game, NimUser user ) {
  
    Nim nim = game.getModelProxy();
    
    // Associazione modello/utente:
    
    user.setModel( nim );
    
    // Avvio della partita: strategia utente
    
    game.takePartInGame( user.userStrategy() );
    
    ( new NimReferee(game,user) ).start();    // Determinazione risultato finale
  }
  
  
  // Avvio dell'applicazione standalone
  
  public static void main( String[] args ) {
  
    JFrame frame = new JFrame( "N I M" );
    frame.setSize( 500, 500 );
    
    Image matchImg = ( Toolkit.getDefaultToolkit() ).getImage( "images/match.png" );
    
    setUp( matchImg, frame.getContentPane() );
    
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.setVisible( true );
  }

}  // test class ClientTest
