package exemploLogging;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LoggingManual {
  public static void main( String[] args ) {
    int port = 5000;
    try {
      switch( args.length ) {
        case 0:
          break;  // use default ....
        case 1:
          port = Integer.parseInt(args[0]);
          break;
        default:
          System.err.println("Uso: java LoggingManual <porta>");
          System.exit(1);
        }
    } catch( NumberFormatException exc ) {
      System.err.println("numero da porta: " + args[0] + " nao eh valido!");
      System.exit(2);
    }
    System.out.println("Parametro porta = " + port);

    // Interacao com client
    ServerSocket server = null;
    try {
      server = new ServerSocket(port);
    } catch( IOException exc ) {
      System.err.println("erro ao criar socket na porta " + port + ": " +
                         exc.getMessage());
      exc.printStackTrace();
      System.exit(3);
    }

    Socket clientSocket = null;
    try {
      System.out.println("Esperando conexao de cliente na porta: " + port);
      clientSocket = server.accept();
      System.out.println("conexao recebida de " + clientSocket.getInetAddress());

      // codigo para tratar conexao aqui 
      talkToClient(clientSocket);

    } catch( IOException exc ) {
      System.err.println("erro aceitando conexoes: " + exc.getMessage());
      exc.printStackTrace();
      System.exit(4);
    } finally {
      try {
        server.close();
        System.out.println("conexao servidor fechada");
      } catch( IOException exc ) {
        System.err.println("erro fechando socket: " + exc.getMessage());
        exc.printStackTrace();
        System.exit(5);
      }
    }
  }

  private static void talkToClient( Socket clientSocket ) {
    PrintWriter out = null;
    BufferedReader in = null;
    try {
      out = new PrintWriter(clientSocket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      String inputLine;
      String outputLine;
      KnockKnockProtocol kkp = new KnockKnockProtocol();

      outputLine = kkp.processInput(null);
      out.println(outputLine);

      while( (inputLine = in.readLine()) != null ) {
        outputLine = kkp.processInput(inputLine);
        out.println(outputLine);
        if( outputLine.equals("Bye.") ) {
          break;
        }
      }
      out.close();
      in.close();
      clientSocket.close();
      out.close();
    } catch( IOException ex ) {
      Logger.getLogger(LoggingManual.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}
