package enterpriseserver.socket;

import inventario.entity.Item;
import inventario.facade.remote.ItemFacadeRemote;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;


public class ServidorThread extends Thread {

	protected static final int timeout_tiempo = 3600000;
	private Socket socket = null;
	
	public ServidorThread(Socket socket) {

		super("Cliente: " + socket);
		this.socket = socket;
		
		try{
			socket.setSoTimeout (timeout_tiempo);
			}
		catch (SocketException se)
		{
			System.err.println ("No se puede setear SetSoTime");
		}
		
	}


    @Override
	public void  run(){
		System.out.println ("Iniciando Soccket["+ socket + "]");
		BufferedReader inCliente;
		String inputLine = null;
		try {
			
			inCliente = new BufferedReader(
					new InputStreamReader(this.socket.getInputStream()));

			while ((inputLine = inCliente.readLine()) != null){
                PrintWriter outCliente = new PrintWriter(socket.getOutputStream(), true);
			    System.out.println("SALIDA TERMINAL["+ inputLine.length() + "]:" + inputLine);
			    

                if (inputLine.equals("i")) {
                    List<Item> items = lookupItemFacade().findAll();
                    for (int i = 0; i < items.size(); i++) {
                        outCliente.println(items.get(i).getItem_name());
                    }
                }
                else{
                    outCliente.println("Echo" + inputLine);
                }
			}
			
		}
	    catch (InterruptedIOException iioe){
			System.out.println ("Timeout ["+ socket + "]"); 
		} 
	    catch(SocketException e){
			System.out.println ("Socket Cerrado ["+ socket + "]"); 
		}
		catch (IOException e) {
			e.printStackTrace();
	    }
		
		System.out.println("Se Desconeto[" + socket + "]");

	}

    private ItemFacadeRemote lookupItemFacade() {
        try {
            Properties props = new Properties();
            props.setProperty("java.naming.factory.initial","com.sun.enterprise.naming.SerialInitContextFactory");
            props.setProperty("java.naming.factory.url.pkgs","com.sun.enterprise.naming");
            props.setProperty("java.naming.factory.state","com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
            props.setProperty("org.omg.CORBA.ORBInitialHost", "127.0.0.1");
            // optional.  Defaults to 3700.  Only needed if target orb port is not 3700.
            props.setProperty("org.omg.CORBA.ORBInitialPort", "3795");
            Context c = new InitialContext(props);
            return (ItemFacadeRemote) c.lookup("inventario.facade.remote.ItemFacadeRemote");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }


	
}
