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;

public class listagem2 {

  public static void main( String[] args ) {

    int port = 0;
    MyLogger logger = new MyLogger();
    
    if ( args.length != 1 ) {
      logger.error( "Uso: java listagem2 <porta>" );
      System.exit(1);
    }

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

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

    ServerSocket server = null;

    try {
      server = new ServerSocket( port );
    }
    catch( IOException exc ) {
      logger.error( "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.error( "erro aceitando conexoes", exc );
      System.exit(4);
    } finally {
      try {
        server.close();
      } catch( IOException exc ) {
        logger.error( "erro fechando socket", exc );
        System.exit(5);
      }
    }
  }
    private static void talkToClient( Socket clientSocket, MyLogger 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.error( "erro fechando socket", ex );
        System.exit(6);
    }
  }

}
