import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;

public class Calculator 
{
   public static void main(String[] args) throws Exception
	{  
		CalculatorFrame frame;
		frame = new CalculatorFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.show();
   }
}

class CalculatorFrame extends JFrame 
{
   public CalculatorFrame() throws Exception
   {
      setTitle("Cliente Calculadora");
      Container contentPane = getContentPane();
		CalculatorPanel panel = new CalculatorPanel(this);
      contentPane.add(panel);
		//setSize(200,400);      
		pack();
   }
}

class CalculatorPanel extends JPanel
{  
   private JLabel display;
	private JFrame frame;
   private JPanel panel;
	private JTextField texto;
   private double result;
   private String lastCommand;
   private boolean start;
	private DataOutputStream outToServer;
	private BufferedReader inFromServer;
	private Socket clientSocket;
	private boolean busy = false;
	private boolean resp = false;
	private String sentence="cliente";
   private String modifiedSentence;
   private String close = "close";

	
   public CalculatorPanel(CalculatorFrame f) throws Exception
   {  
		frame = f;
      setLayout(new BorderLayout());
      result = 0;
      lastCommand = "=";
      start = true;
		setInicio();
		//setButton();
   }
	
	private void setInicio()
	{
		panel = new JPanel();
      panel.setLayout(new GridLayout(3, 1));
		display = new JLabel("Ingrese la direccion del servidor:");
      panel.add(display, BorderLayout.NORTH);
		texto = new JTextField("IPServidor"); 
		panel.add(texto);
		ActionListener aceptar = new AceptarAction(this);
	  	JButton ok = new JButton("Intentar Conectar");	
		ok.addActionListener(aceptar);
     	panel.add(ok);
		add(panel, BorderLayout.CENTER);
	}
	
	private class AceptarAction implements ActionListener
 	{
		private CalculatorPanel calc;
		public AceptarAction(CalculatorPanel c)
		{
			calc = c;
		}
  	   public void actionPerformed(ActionEvent e)
     	{  
			boolean conectado = false;
			try 
			{
  				clientSocket = new Socket(texto.getText(), 6789);
				conectado = true;
			}
			catch(IOException event) 
			{
				texto.setText("Ingrese Direccion IP Nuevamente");
			}
			try 
			{
	   	   outToServer = new DataOutputStream(clientSocket.getOutputStream());
 	   	   inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
				System.out.println("Conexion aceptada \nIngrese sus calculos solo + - / y * y use espacio para separar elementos y/o números , para finalizar escriba  close");
	 		  	outToServer.writeBytes(sentence + '\n');
			}
			catch(IOException event) 
			{
				System.out.printf("Error comunicacion con servidor");
				System.exit(-1);
			}
			if(conectado)
			{
				calc.removeAll();
				setButton();
				calc.validate();
				System.out.println("Llege aca");
			}
		}
  	}
		
	private void setButton()
	{
		display = new JLabel("0");
  	   add(display, BorderLayout.NORTH);
		panel = new JPanel();
	   ActionListener insert = new InsertAction();
      ActionListener command = new CommandAction();
      panel.setLayout(new GridLayout(4, 5));
      addButton("7", insert);
      addButton("8", insert);
      addButton("9", insert);
      addButton("/", insert);
		addButton("Clr", insert);
      addButton("4", insert);
      addButton("5", insert);
      addButton("6", insert);
      addButton("*", insert);
		addButton("Ins", insert);
      addButton("1", insert);
      addButton("2", insert);
      addButton("3", insert);
      addButton("-", insert);
		addButton("=", command);
		addButton(".", insert);    
		addButton("0", insert);
      addButton("+", insert);
		add(panel, BorderLayout.CENTER);
		frame.pack();
	}

   private void addButton(String label, ActionListener listener)
   {  
      JButton button = new JButton(label);
      button.addActionListener(listener);
      panel.add(button);
   }
	
   public void calculate(String calculo)
	{
			String modifiedSentence = new String();
			try 
			{
        		outToServer.writeBytes(calculo + '\n');
			}
			catch(IOException e)
			{
				System.out.println("Error comunicacion con servidor");
				//clientSocket.close();
				System.exit(-1);
			}
			try
			{
				modifiedSentence = inFromServer.readLine();
			}
			catch(IOException e)
			{
			}
			//System.out.println("FROM SERVER:  La respuesta es :" + modifiedSentence);
		if (modifiedSentence.compareTo("none") == 0)
		{
			System.out.println("Error de Calculo");
			//Ventana ventana = new Ventana("Error de Calculo");
		}
		else if (modifiedSentence.compareTo("noneD") == 0)
		{
			System.out.println("Sin Calculadora");
			//Ventana ventana = new Ventana("Todas las Calculadoras se Encuentra Ocupadas\nIntentelo Mas Tarde");
		}
  		else
		{
	      display.setText(modifiedSentence);
			resp = true;
		}
   }

   private class InsertAction implements ActionListener
   {
      public void actionPerformed(ActionEvent e)
      {
         String input = e.getActionCommand();
			//System.out.println(input);
			if((start)&&!((input.compareTo("*")==0)||(input.compareTo("/")==0)||(input.compareTo("+")==0)||(input.compareTo("Clr")==0)||(input.compareTo("Ins")==0)))
			{
				//System.out.println("Pico");
				display.setText(input);
				start = false;
			}
			else if((resp)&&(!start))
			{
				if((input.compareTo("*")==0)||(input.compareTo("/")==0)||(input.compareTo("-")==0)||(input.compareTo("+")==0))
				{
					display.setText(display.getText() + input);
					resp = false;
				}
				else if((input.compareTo("Ins")==0))
				{
					String texto = display.getText();
					int largo = texto.length();
				//	System.out.println(texto + " Largo: "+ largo);
					if(largo-1 == 0)
					{
						display.setText("0");
						start = true;
						resp = false;
					}
					else
					{
						display.setText(texto.substring(0,largo-1));
						resp = false;
					}

				}
				else if((input.compareTo("Clr")==0))
				{
						display.setText("0");
						start = true;
				}
				else
				{
         		display.setText(input);
					resp = false;
				}
			}
			else if(!start)
			{
				if((input.compareTo("Ins")==0))
				{
					String texto = display.getText();
					int largo = texto.length();
					//System.out.println(texto + " Largo: "+ largo);
					if(largo-1 == 0)
					{
						display.setText("0");
						start = true;
						resp = false;
					}
					else
					{
						display.setText(texto.substring(0,largo-1));
						resp = false;
					}

				}
				else if((input.compareTo("Clr")==0))
				{
						display.setText("0");
						start = true;
						resp = false;
				}
				else
				{
					display.setText(display.getText() + input);
					resp = false;
				}
			}
      }
   }

/*	private class Ventana extends JFrame 
	{
 		public Ventana(String texto)
   	{
   	   setTitle("Aviso");
    		Container contentPane = getContentPane();
			ventanaPanel panel = new ventanaPanel(texto, this);
 	     	contentPane.add(panel);
 	     	pack();
   	}
	}
	
	private class ventanaPanel extends JPanel
	{
		public ventanaPanel(String Texto, Ventana ventana)
		{
			//ventana.add(new 
		}
	}*/
	
   private class CommandAction implements ActionListener
   {
      public void actionPerformed(ActionEvent e)
      {  
         //String command = e.getActionCommand();

			if((!busy)&&(!start))
			{
				busy = true;
				calculate(display.getText());
				//System.out.println(calculo);
				busy = false;
			}
      }
		

	}
}


