package ecies_java;

import java.awt.EventQueue;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JLabel;
import java.awt.Font;

public class server111 
  {
	static ServerSocket ss;
	static Socket s;
	
	
	
	static OutputStream os = null;
    static OutputStreamWriter osw = null;
    static BufferedWriter bw = null;
	
	private JFrame serverfrm;
	private static JTextArea server_screen;
	private JButton btnExit;
//	private JButton btnCleanbtn;

	/**
	 * Launch the application.
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException 
	  {
		EventQueue.invokeLater(new Runnable() 
		 {public void run() {
				try 
				  {
					server111 window = new server111();
					window.serverfrm.setVisible(true);
				   } 
				catch (Exception e) 
				  {e.printStackTrace();
				}
			}
		  });
	    ///////////////////////////////
        int clientNumber = 0;
        ServerSocket listener = new ServerSocket(3333);
        try 
          {
           while (true)
             {new ServerThread(listener.accept(), clientNumber++).start();}
           } 
        finally 
           {listener.close();}
	    //////////////////////////////		
	}

	/**
	 * Create the Server application.
	 */
	public server111() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		serverfrm = new JFrame();
		serverfrm.getContentPane().setBackground(Color.WHITE);
		serverfrm.setBackground(Color.WHITE);
		serverfrm.setTitle("frm0");
		serverfrm.setBounds(100, 100, 763, 564);
		serverfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		serverfrm.getContentPane().setLayout(null);
		
		server_screen = new JTextArea();
		server_screen.setBackground(Color.LIGHT_GRAY);
		server_screen.addAncestorListener(new AncestorListener() {
			public void ancestorAdded(AncestorEvent event) {
			}
			public void ancestorMoved(AncestorEvent event) {
			}
			public void ancestorRemoved(AncestorEvent event) {
			}
		});
		server_screen.setBounds(31, 126, 695, 343);
		serverfrm.getContentPane().add(server_screen);
		
		btnExit = new JButton("Exit");
		btnExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		btnExit.setBounds(12, 506, 86, 25);
		serverfrm.getContentPane().add(btnExit);
		
		JLabel lblServerApplication = new JLabel("Server");
		lblServerApplication.setFont(new Font("Dialog", Font.BOLD, 45));
		lblServerApplication.setBounds(131, 34, 542, 67);
		serverfrm.getContentPane().add(lblServerApplication);

		
		
		
	}

   
//*****************************************************************
	private static class ServerThread extends Thread 
    {
     private Socket socket;
     private int clientNumber;

     public ServerThread(Socket socket, int clientNumber) 
       {  
  	    this.socket = socket;
          this.clientNumber = clientNumber;
        }


      public void run()
        {
    	  try
    	  {    		   
    	// path received file
           String workingDirectory = System.getProperty("user.dir");
           String absoluteFilePath = workingDirectory + File.separator +"file2.txt";
          
           
           while (true) {
               
               // Variable to received data
               InputStream is = s.getInputStream();
               
               receive_bytes_from_client(is,absoluteFilePath);
               server_screen.append("The server received file1");         
           }
    	      	   
    	  }
    	  catch(Exception e)
    	  {System.out.println("Error with receive and send message: server side");}        
    }
      
    }
	// This method to receive bytes from client and store as file
    public static void receive_bytes_from_client(InputStream is,String absoluteFilePath)
      {
    	 int filesize = 10000;int bytesRead; int currentTot;
         
         try
           {
            File received_file_name = new File(absoluteFilePath);
            // Variable to receive data with byte
            byte[] bytearray = new byte[filesize];
            // To store received file to file path
            FileOutputStream fos_s = new FileOutputStream(received_file_name);
            BufferedOutputStream bos_s = new BufferedOutputStream(fos_s);
            //Read received data
            bytesRead = is.read(bytearray, 0, bytearray.length);
            currentTot = bytesRead;
            do 
              {// Continue to read other received bytes
               bytesRead = is.read(bytearray, currentTot,(bytearray.length - currentTot));
               if (bytesRead >= 0)
                  currentTot += bytesRead;
               } 
            while (bytesRead > -1);
            // store file
            bos_s.write(bytearray, 0, currentTot);
            bos_s.flush();
            bos_s.close();
           }
         catch(Exception ex)
         {System.out.println("Error received");}
    	
      }
	
}
