package br.senacpos.turma02;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.*;

public class listagem3 {

  public static void main( String[] args ) {

    int port = 0;
    Logger logger = Logger.getLogger("listagem3");

    // configuracao do logger
    String LOGGER_FILE = "listagem3.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." );
    }
    

    if ( args.length != 1 ) {
      logger.severe( "Uso: java listagem3 <porta>" );
      System.exit(1);
    }

    try {
      port = Integer.parseInt( args[0] );
    }
    catch( NumberFormatException exc ) {
      logger.severe( args[0] + " nao e um numero valido!" );
      System.exit(2);
    }

    logger.config( "Parametro porta = " + port );

    
    ServerSocket server = null;

    try {
      server = new ServerSocket( port );
    }
    catch( IOException exc ) {
      logger.log( Level.SEVERE, "erro ao criar socket na porta " + port, exc );
      System.exit(3);
    }

    try {
      Socket socket = server.accept();
      logger.info( "Conexao recebida do host " + socket.getInetAddress() );
      // codigo para tratar conexao aqui
      talkToClient(socket, logger);
      
    } catch( IOException exc ) {
      logger.log( Level.SEVERE, "erro aceitando conexoes", exc );
      System.exit(4);
    } finally {
      try {
        server.close();
      } catch( IOException exc ) {
        logger.log( Level.SEVERE, "erro fechando socket", exc );
        System.exit(5);
      }
    }
  }
    private static void talkToClient( Socket clientSocket, Logger logger ) {
    PrintWriter out = null;
    BufferedReader in = null;
    try {
	out = new PrintWriter(clientSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        String inputLine, outputLine;

        logger.info( "vai ler mensagem do client <- " + clientSocket.getInetAddress() );
        if( (inputLine=in.readLine()) != null ) {
          logger.info( "mensagem do client: " + inputLine );
	}

        logger.info( "envia mensagem para o client -> " + clientSocket.getInetAddress() );
	outputLine = "bye";
        out.println(outputLine);

        out.close();
        in.close();
        clientSocket.close();
        out.close();
    } catch( IOException ex ) {
        logger.severe( "erro fechando socket " );
        System.exit(6);
    }
  }
}
