package test_gui04;

import javax.swing.event.*;

import java.awt.event.*;

import javax.swing.*;

import java.awt.*; 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Vector;
import java.io.*;
import java.net.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class Main extends JFrame implements ActionListener
{
	
	JButton btn_ctrl1 ,btn_ctrl2, btn_ctrl3, btn_ctrl4, btn_fichier,btn_fullduplex ;
	JLabel label1, label2, label3, label4;
	ImageIcon imageIcon1,imageIcon2,imageIcon3,imageIcon4;
	
	public static BufferedWriter os = null;
	public static BufferedReader is = null;
	
	public static Socket clientSocket = null;	
	
	String etat_btn_ctrl1 ="red";
	String etat_btn_ctrl2 ="red";
	String etat_btn_ctrl3 ="red";
	String etat_btn_ctrl4 ="red";
	
	
	public Main() 
	{
	    setTitle("Appli Client - 2016");
	    setSize( 500, 500 );

	    // icon de l'appli
	    Image img = Toolkit.getDefaultToolkit().getImage("d:/client.png");
	    setIconImage(img);

		getContentPane().setLayout(new BorderLayout()); 
		StatusBar statusBar = new StatusBar(); 
		
		Container pane = getContentPane();
		
		//pane.setLayout(null); // disable layout manager - use absolute layout
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		/*
		addWindowListener(new WindowAdapter() { 
		
			public void windowClosing(WindowEvent event) 
			{
					System.exit(0); 
			}
		}); 

		*/
	    
	    pane.setLayout(null);
	    
	    String text = "A JTextArea object represents a multiline area for displaying text. "
	            + "You can change the number of lines that can be displayed at a time, "
	            + "as well as the number of columns. You can wrap lines and words too. "
	            + "You can also put your JTextArea in a JScrollPane to make it scrollable.";
	    
	    JTextArea textArea2 = new JTextArea(text, 5, 10);
	    textArea2.setPreferredSize(new Dimension(100, 100)); 
	    JScrollPane scrollPane = new JScrollPane(textArea2, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
	    textArea2.setLineWrap(true);
	    pane.add(scrollPane);
	    scrollPane.setBounds(150 , 330, 250, 50);	
	    
	    JButton btn_connexion = new JButton("Connexion");
	    btn_connexion.addActionListener(new action_btn_connexion()); 
	    
	    JButton btn_retourne_datas = new JButton("Retourne datas");
	    btn_retourne_datas.addActionListener(new action_btn_retourne_datas()); 
	    
	    JButton btn_cmd1 = new JButton("Cmd 1");
	    btn_cmd1.addActionListener(new action_btn_cmd1()); 
	    
	    btn_fichier = new JButton("fichier");
	    btn_fichier.addActionListener(this); 
	    btn_fichier.setBounds(250 , 25, 150 , 50);
	    
	    
	    btn_fullduplex = new JButton("FullDuplex");
	    btn_fullduplex.addActionListener(this); 
	    btn_fullduplex.setBounds(250 , 100, 150 , 50);
	    
	   // MyButtonListener listener = new MyButtonListener();
	    
	    btn_ctrl1 = new JButton("IO1");
	    //btn_ctrl1.addActionListener(new action_btn_ctrl1()); 
	    btn_ctrl1.addActionListener(this);

	    btn_ctrl2 = new JButton("IO2");
	    btn_ctrl2.addActionListener(this);
	    
	    btn_ctrl3 = new JButton("IO3");
	    btn_ctrl3.addActionListener(this);
	    
	    btn_ctrl4 = new JButton("IO4");
	    btn_ctrl4.addActionListener(this);
	    
	    imageIcon1 = new ImageIcon("d:/red_32x32.png");
	    label1 = new JLabel(imageIcon1);
	    ImageIcon imageIcon2 = new ImageIcon("d:/red_32x32.png");
	    label2 = new JLabel(imageIcon2);
	    ImageIcon imageIcon3 = new ImageIcon("d:/red_32x32.png");
	    label3 = new JLabel(imageIcon3);
	    ImageIcon imageIcon4 = new ImageIcon("d:/red_32x32.png");
	    label4 = new JLabel(imageIcon4);
	    
	    btn_connexion.setBounds(25 , 20, 150 , 50);
	    btn_retourne_datas.setBounds(25 , 80, 150 , 50);
	    btn_cmd1.setBounds(25 , 140, 150 , 50);
	    
	    btn_ctrl1.setBounds(25 , 250, 60 , 50);
	    btn_ctrl2.setBounds(100 , 250, 60 , 50);
	    btn_ctrl3.setBounds(175 , 250, 60 , 50);
	    btn_ctrl4.setBounds(250 , 250, 60 , 50);
	    
	    label1.setBounds(25 , 200, 60 , 50);
	    label2.setBounds(100 , 200, 60 , 50);
	    label3.setBounds(175 , 200, 60 , 50);
	    label4.setBounds(250 , 200, 60 , 50);
		    
	    //http://icons.vrx.net/parts/buttons/green/
	    
	    pane.add(btn_connexion);
	    pane.add(btn_retourne_datas);
	    pane.add(btn_cmd1);

	    pane.add(btn_ctrl1);
	    pane.add(btn_ctrl2);
	    pane.add(btn_ctrl3);
	    pane.add(btn_ctrl4);
	    pane.add(label1);
	    pane.add(label2);
	    pane.add(label3);
	    pane.add(label4);
	    pane.add(btn_fichier);
	    pane.add(btn_fullduplex);
	    
	    //JButton b4 = new JButton("4");
	    //JButton b5 = new JButton("5");
	    //pane.add(b4);
	    //pane.add(b5);
	    //Insets insets = pane.getInsets();
	    //Dimension size = btn_connexion.getPreferredSize();
	    //b4.setBounds(50 , 300, 50, 14); // x, y, largeur, hauteur
	    //b5.setBounds(50 , 350, 50, 14);
	    
	    this.setLayout(new BorderLayout());
	    //getContentPane().add(BorderLayout.SOUTH, statusBar); 
		pane.add(BorderLayout.SOUTH, statusBar); 
		
	} 
	
        public void actionPerformed(ActionEvent e)
        {
        	TCP_communication id ;         // définition de la variable référence
    		id = new TCP_communication(); // création de l’instance
    	//	id.send_cmd("cmd_gpio");
          
            if(e.getSource() == btn_ctrl1) 
            {
            	
            	if(etat_btn_ctrl1 == "red")
            	{	
            		System.out.println("Un est allumé");
            		etat_btn_ctrl1 = "green";
            		label1.removeAll();
            		imageIcon1 = new ImageIcon("d:/green_32x32.png");
            		label1.setIcon(imageIcon1);
            	}
            	else 
            	{	 
            		System.out.println("Un est éteint");
            		etat_btn_ctrl1 = "red";
            		label1.removeAll();
                	imageIcon1 = new ImageIcon("d:/red_32x32.png");
                	label1.setIcon(imageIcon1);
            		
            	}
            	
            
            }

            if(e.getSource() == btn_ctrl2) 
            {
            	if(etat_btn_ctrl2 == "red")
            	{	
            		System.out.println("Deux est allumé");
            		etat_btn_ctrl2 = "green";
            		label2.removeAll();
            		imageIcon2 = new ImageIcon("d:/green_32x32.png");
            		label2.setIcon(imageIcon2);
            	}
            	else 
            	{	 
            		System.out.println("Deux est éteint");
            		etat_btn_ctrl2 = "red";
            		label2.removeAll();
                	imageIcon2 = new ImageIcon("d:/red_32x32.png");
                	label2.setIcon(imageIcon2);
            		
            	}

            }

            if(e.getSource() == btn_ctrl3) 
            {
            	if(etat_btn_ctrl3 == "red")
            	{	
            		System.out.println("Trois est allumé");
            		etat_btn_ctrl3 = "green";
            		label3.removeAll();
            		imageIcon3 = new ImageIcon("d:/green_32x32.png");
            		label3.setIcon(imageIcon3);
            	}
            	else 
            	{	 
            		System.out.println("Trois est éteint");
            		etat_btn_ctrl3 = "red";
            		label3.removeAll();
                	imageIcon3 = new ImageIcon("d:/red_32x32.png");
                	label3.setIcon(imageIcon3);
            		
            	}	

            }

            if(e.getSource() == btn_ctrl4) 
            {
            	if(etat_btn_ctrl4 == "red")
            	{	
            		System.out.println("Quatre est allumé");
            		etat_btn_ctrl4 = "green";
            		label4.removeAll();
            		imageIcon4 = new ImageIcon("d:/green_32x32.png");
            		label4.setIcon(imageIcon4);
            	}
            	else 
            	{	 
            		System.out.println("Quatre est éteint");
            		etat_btn_ctrl4 = "red";
            		label4.removeAll();
                	imageIcon4 = new ImageIcon("d:/red_32x32.png");
                	label4.setIcon(imageIcon4);
            		
            	}

            }
            
            if(e.getSource() == btn_fichier) 
            {
            		
            		System.out.println("Fonction fichier");
            	
            		try {
						writeFile();
						File fin = new File("_out.txt");
						readFile(fin);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
            }
            
            /// essai
            if(e.getSource() == btn_fullduplex) 
            {
            	 	id.send_cmd("cmd_fullduplex");
            		id.retour();
            }
            
            
        }
//    }
        
        
        public static void writeFile() throws IOException
        {
        	FileWriter fw = new FileWriter("_out.txt");
         
        	for (int i = 0; i < 10; i++) {
        		fw.write("something" + "\n");
        		
        	}
         
        	fw.close();
        	
        	
        	
        }  
        
        public static void readFile(File fin) throws IOException 
        {
        	Vector lineArray=new Vector();
        	BufferedReader br = new BufferedReader(new FileReader(fin));
        	
         
        	int[] monTableau=new int[5];
        	 monTableau[1] = 454664;
        	
        	String line = null;
        	while ((line = br.readLine()) != null)
        	{
        		lineArray.add(line);
        		System.out.println(line);
        	}
         
        	br.close();
        }
	
	public static void tcp() 
	{ 
	     System.out.println("TRACE");
	
	}
	
	
	public static void main(String[] args) 
	{ 
		(new Main()).show(); 
	}
} 



class TCP_communication 
{
	 	Socket socketOfClient;

		void send_cmd(String cmd)
		{
			 String serverHost = "82.234.53.234"; //"localhost";
			 //serverHost = "localhost";

			 try
			 {
				socketOfClient = new Socket(serverHost, 8081);
				// envoi une commande au serveur
				PrintWriter pw = new PrintWriter(socketOfClient.getOutputStream(), true);
				pw.println(cmd);
				//socketOfClient.close();
				System.out.println("***** " + cmd);
			} 
			catch (IOException e) 
			{
				System.out.println(e);
			}
			
		}
		
		void receive(String msg)  
		  {
		  	try {
			   byte[] mybytearray = new byte[1024];
			    InputStream is = socketOfClient.getInputStream();
			    FileOutputStream fos = new FileOutputStream("d:/xs.txt");
			    BufferedOutputStream bos = new BufferedOutputStream(fos);
			    int bytesRead = is.read(mybytearray, 0, mybytearray.length);
			    bos.write(mybytearray, 0, bytesRead);
			    
			    System.out.println("Reception du fichier"+msg);
			    
			   bos.close();
			    socketOfClient.close();
		  	}
		  	catch (IOException e) 
			{
				System.out.println(e);
			}

		  }
		void retour()
		{
			try {
				  
				 InputStream s1In = socketOfClient.getInputStream();
        		 DataInputStream dis = new DataInputStream(s1In);
        		 String st = new String (dis.readUTF());
        		 System.out.println("Réponse --> : " + st);
			     socketOfClient.close();
			  	}
			catch (IOException e) 
				{
					System.out.println(e);
				}

			
		}	
		
		
		

}

class toto 
{
	
	public toto() 
	{

			String serverHost = "localhost";
			 
		    Socket socketOfClient;
		    try {
					socketOfClient = new Socket(serverHost, 8081);
					 
					 // envoi un message au serveur
					 BufferedReader br = new BufferedReader(new InputStreamReader(socketOfClient.getInputStream()));
					 PrintWriter pw = new PrintWriter(socketOfClient.getOutputStream(), true);
					 pw.println("Salut Serveur");
					
					 // voici la réponse du serveur
					 InputStream s1In = socketOfClient.getInputStream();
					 DataInputStream dis = new DataInputStream(s1In);
					 String st = new String (dis.readUTF());
					 System.out.println(st);
					 // When done, just close the connection and exit
					 dis.close();
					 s1In.close();
					 socketOfClient.close();
			} 
		    
		    catch (UnknownHostException e)
		    {
				// TODO Auto-generated catch block
				e.printStackTrace();
                System.out.println(e.toString());
			} 
		    catch (IOException e) 
		    {
				// TODO Auto-generated catch block
				e.printStackTrace();
                System.out.println(e.toString());
			} 

	}
    
}

class action_btn_connexion implements ActionListener 
{
	public void actionPerformed(ActionEvent e)
	{
		//int mc = JOptionPane.WARNING_MESSAGE;
		//String str = JOptionPane.showInputDialog (null, "Enter text:", "Title", mc);
		
		JOptionPane.showMessageDialog(null, "Attention" );
		
		toto tcp = new toto(); 
		//		aaa.tcp();
		//		System.exit(0);
	}
}


class action_btn_retourne_datas implements ActionListener
{
	public void actionPerformed(ActionEvent e) 
	{
		
		//int mc = JOptionPane.WARNING_MESSAGE;
		//String str = JOptionPane.showInputDialog (null, "Enter text:", "Title", mc);
		
		//JOptionPane.showMessageDialog(null, "Retour du fichier" );
		TCP_communication b ;         // définition de la variable référence
		b = new TCP_communication(); // création de l’instance
		b.send_cmd("echange_fichier");
	//	b.send_cmd("echange_fichier");
	
		 b.receive("pipo"); 
	}
}


class action_btn_cmd1 implements ActionListener
{
	public void actionPerformed(ActionEvent e) 
	{
		
		//int mc = JOptionPane.WARNING_MESSAGE;
		//String str = JOptionPane.showInputDialog (null, "Enter text:", "Title", mc);
		
		//JOptionPane.showMessageDialog(null, "Bouton Cmd1" );
		TCP_communication a ;         // définition de la variable référence
		a = new TCP_communication(); // création de l’instance
		a.send_cmd("cmd_start");
		
	}
}


class action_btn_ctrl1 implements ActionListener
{
	public void actionPerformed(ActionEvent e) 
	{
		
		JOptionPane.showMessageDialog(null, "CTRL1" );
		
		 Object  source=e.getSource();
		
		 
         System.out.println(source);
		 
		/* if (e.getSource() == btn_ctrl1) 
		 {
		 
		//label1
		/*if(e.getSource().equals(b))
        {
            this.l.setText("Testing");
        }*/
		
	}
}



class StatusBar extends JPanel implements ActionListener
{
	private JLabel statusLabel;

	public StatusBar()
	{
		SimpleDateFormat sdf = new SimpleDateFormat( "dd MMM yyyy kk:mm:ss" );
		String hhh =  sdf.format( new GregorianCalendar().getTime() ) ;
		
		setLayout(new BorderLayout(3, 3)); 
		statusLabel = new JLabel(hhh); 
		statusLabel.setBorder(BorderFactory.createLoweredBevelBorder()); 
		statusLabel.setForeground(Color.black);
		add(BorderLayout.CENTER, statusLabel); 
		
		JLabel dummyLabel1 = new JLabel(" Ver 1.0 "); 
		dummyLabel1.setBorder(BorderFactory.createLoweredBevelBorder()); 
		add(BorderLayout.EAST, dummyLabel1); 

//		JLabel Label2 = new JLabel(" hrqzq "); 
//		Label2.setBorder(BorderFactory.createLoweredBevelBorder()); 
//		add(BorderLayout.WEST, Label2); 

		 ImageIcon imageIcon = new ImageIcon("d:/server.png");
		 JLabel Label2 = new JLabel(imageIcon);
		 Label2.setBorder(BorderFactory.createLoweredBevelBorder()); 
		 add(BorderLayout.WEST, Label2); 

		
		   Timer t = new Timer(1000, this);
		    t.start( );
	} 
	
	@Override
	public void actionPerformed(ActionEvent e) 
	{
		// TODO Auto-generated method stub
		  SimpleDateFormat sdf = new SimpleDateFormat( "dd MMM yyyy kk:mm:ss" );
		  String hhh =  sdf.format( new GregorianCalendar().getTime() ) ;
		  statusLabel.setText(hhh);
	}
}
