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.*;

public class ExemploLogging {
  public static void main(String[] args) {
    int port = 5000;
    Logger logger = Logger.getLogger("jm.logging.exemplo");
    try {
      switch( args.length ) {
        case 0:
          break;  // use default ....
        case 1:
          port = Integer.parseInt(args[0]);
          break;
        default:
          logger.severe("Uso: java ExemploLogging <porta>");
          System.exit(1);
        }
    } catch( NumberFormatException exc ) {
      logger.severe("numero da porta: " + args[0] + " nao eh valido!");
      System.exit(2);
    }
    logger.config("Parametro porta = " + port);
    
    // configuracao do logger
    String LOGGER_FILE = "ExemploLogging.log";
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(Level.ALL);
    logger.addHandler(ch);
    logger.setLevel(Level.ALL);
    logger.setUseParentHandlers(false);
   
    FileHandler fh = null;
    SimpleFormatter sf = new SimpleFormatter();
    try {
      fh = new FileHandler(LOGGER_FILE, 50000, 1);
      fh.setFormatter(sf);
      logger.addHandler(fh);
    }
    catch(IOException exc) {
      logger.warning("nao foi possivel abrir o arquivo " + LOGGER_FILE +
                      " para logging. Usando apenas o console.");
    }  

    // Interacao com client
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(port);
    } catch(IOException exc) {
      logger.log(Level.SEVERE, "erro ao criar socket na porta " + port, exc);
      System.exit(3);
    }
    try {
      logger.info("Esperando conexao de cliente na porta: " + port);
      Socket clientSocket = serverSocket.accept();
      logger.info("Conexao recebida do host " + clientSocket.getInetAddress());
      
      // codigo para tratar conexao aqui 
      talkToClient(clientSocket);
    }
    catch(IOException exc) {
      logger.log(Level.SEVERE, "erro aceitando conexoes", exc);
      System.exit(4);
    }
    finally {
      try {
        serverSocket.close();
        logger.info("conexao servidor fechada");
      }
      catch(IOException exc) {
        logger.log(Level.SEVERE, "erro fechando socket", exc);
        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);
    }
  }
}

