//MMSClient.java
//接收MMSServer送來的檔案
//儲存後..show出
import java.io.*;
import java.io.BufferedOutputStream.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MMSClient extends JFrame implements Runnable{
 private BorderLayout layout;
 private JPanel upPanel,middlePanel,downPanel;
 private JLabel preview,picarea;
 private JButton choosemsg,readmsg,delmsg,connecting,disconnecting;
 private JTextArea status;
 private ImageIcon imageIcon;
 private FileDialog dialog;
 private Thread t1;
 private boolean beChoosemsg=false,beReadmsg=false,beDelmsg=false,beConnecting=false,beDisconnecting=false;

 private BufferedOutputStream FileOutput = null;
 private ObjectOutputStream SocketOutput = null;
 private ObjectInputStream SocketInput = null;
 private Socket connection; 
 private ServerSocket server;
 private static String rootaddr="C:/Messages/";//根目錄的位址
 private String message,Fname="",sendaddr,attdir,preFileName="";
 private int addrindex=0;//紀錄address的char index
 private File MessagesDir; 
 private showpic readMessage;
  
 public MMSClient()
  {
   super("==MMSClient's Control Panel==");

   Container c = getContentPane();
   c.setLayout(new FlowLayout());

   upPanel = new JPanel();
   upPanel.setLayout(new BorderLayout (40,40));
   c.add(upPanel);

   middlePanel = new JPanel();
   middlePanel.setLayout(new BorderLayout (20,20));
   c.add(middlePanel);
 
   downPanel = new JPanel();
   downPanel.setLayout(new BorderLayout (20,20));
   c.add(downPanel);
  
   preview = new JLabel("   圖   片   預   覽  :  ");
   upPanel.add(preview, BorderLayout.NORTH);	

   choosemsg = new JButton(" 選  擇  訊  息 ");
   choosemsg.addActionListener(
   new ActionListener(){
   public void actionPerformed(ActionEvent e)
	   {
	   	 imageIcon = new ImageIcon("");
         picarea = new JLabel("");
		 upPanel.add(picarea,BorderLayout.CENTER);
		 validate();
         beChoosemsg=true;    
		 //小狐修改，這些應該不需要用到thread了
		 //start();
		 openFile();
	   }
     }
   );	
   middlePanel.add(choosemsg, BorderLayout.NORTH);	

   readmsg = new JButton("  讀        取  ");
   readmsg.addActionListener(
   new ActionListener(){
   public void actionPerformed(ActionEvent e)
	   {
         beReadmsg=true;
		 beChoosemsg=false;
		 beDelmsg=false;
		 //小狐修改，這些應該不需要用到thread了
		 //start();
		 readFile();
	   }
     }
   );	
   middlePanel.add(readmsg,BorderLayout.WEST);

   delmsg = new JButton("  刪        除  ");
   delmsg.addActionListener(
   new ActionListener(){
   public void actionPerformed(ActionEvent e)
	   {
         beDelmsg=true;
		 beChoosemsg=false;
		 beReadmsg=false;
		 //小狐修改，這些應該不需要用到thread了
		 //start();
		 deleteFile();
	   }
     }
   );	
   middlePanel.add(delmsg, BorderLayout.EAST);

   status = new JTextArea(6,30);  
   status.setEditable(false); 
   downPanel.add(new JScrollPane(status), BorderLayout.NORTH);

   connecting = new JButton("  連    線  ");
   connecting.addActionListener(
   new ActionListener(){
    public void actionPerformed(ActionEvent e)
	   {
     	  beConnecting=true;
		  beDisconnecting=false;
	      beDelmsg=false;
		  beChoosemsg=false;
		  beReadmsg=false;
		  // 小狐修改，server socket先在這邊開起來
		  try
		  {
			server = new ServerSocket( 65000, 100 );
		  }
		  catch ( IOException io ) {
			io.printStackTrace();
		  }
          start();         
	   }
     }
   );	  
   downPanel.add(connecting, BorderLayout.WEST);

   disconnecting = new JButton("  斷    線  ");
   disconnecting.addActionListener(
   new ActionListener(){
    public void actionPerformed(ActionEvent e)
	   {
     	  beDisconnecting=true;
		  beConnecting=false;
          beDelmsg=false;
		  beChoosemsg=false;
		  beReadmsg=false;
		  // 小狐修改，在這邊把thread給停掉，不要跑了並且把server socket關掉
          //start();    
		  t1.stop();
		  try
		  {
			server.close();	
		  }
		  catch ( IOException io ) {
		    io.printStackTrace();
		  }
 		    status.append("Stop connectting.....\n");
	   }
     }
   );	  
   downPanel.add(disconnecting, BorderLayout.EAST);

    setSize(350,640);//設定視窗的大小
    show();//顯示視窗
 
  } 
//用Thread來控制
public void start()
{
      t1 = new Thread(this,"t1");
      t1.start();
}
public void run()
{
	// 小狐修改，讓thread只跑runClient就好~
    //if (beConnecting)
     //{
      //runClient();
     //}
    //else if (beChoosemsg) 
	//{
      //openFile();
    //}
    //else if (beReadmsg) 
	//{
      //readFile();
    //}
    //else if (beDelmsg) 
	//{
      //deleteFile();
    //}
	//else if (beDisconnecting) 
	//{
      //stopClient();
    //}
	//else
     //{
      //System.out.print("有錯誤喔~~");
     //}
	 runClient();
}

public void openFile()
{
 MessagesDir = new File(rootaddr);
  if(!MessagesDir.exists())
  {
	 MessagesDir.mkdir();		           
  }
 JFileChooser fileChooser = new JFileChooser("C:/Messages/");
 ExampleFileFilter filter = new ExampleFileFilter();
 filter.addExtension("jpg");
 filter.addExtension("gif");
 filter.setDescription("JPG & GIF Images");
 fileChooser.setFileFilter(filter);
 fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
 
 int result = fileChooser.showOpenDialog(this);
 if(result == JFileChooser.CANCEL_OPTION)
	 return;

 File filename = fileChooser.getSelectedFile();
 if(filename == null||filename.getName().equals(""))
	 JOptionPane.showMessageDialog(this,"Invalid File Name","Invalid File Name",JOptionPane.ERROR_MESSAGE);
 else{
     preFileName = filename.getName();     
	 imageIcon = new ImageIcon (rootaddr+preFileName);
     picarea = new JLabel(imageIcon,SwingConstants.CENTER);
	 // 小狐新增
	 upPanel.removeAll();
     upPanel.add(picarea,BorderLayout.CENTER);
	 upPanel.add(preview, BorderLayout.NORTH);
	 //upPanel.add(choosemsg, BorderLayout.EAST);
	 validate();	 
	 System.out.println(preFileName);
 }
}

public void readFile()
{
	if(preFileName == "")
      JOptionPane.showMessageDialog(null, "請選擇欲讀取的訊息~~", "Warning", JOptionPane.INFORMATION_MESSAGE);
	else
    {
	  readMessage=new showpic();
      readMessage.startShow(rootaddr+preFileName,rootaddr+"addr"+preFileName.substring(0, preFileName.indexOf('.'))+".txt");
	}
	  imageIcon = new ImageIcon("");
      picarea = new JLabel("");
	  upPanel.add(picarea,BorderLayout.CENTER);
	  validate();
	  preFileName="";

}

public void deleteFile()
{
  if(preFileName == "")
      JOptionPane.showMessageDialog(null, "請選擇欲刪除的訊息~~", "Warning", JOptionPane.INFORMATION_MESSAGE);
 else
   {
  File fp = new File(rootaddr+preFileName);
  File fa = new File(rootaddr+"addr"+preFileName.substring(0, preFileName.indexOf('.'))+".txt");
    if(fp.delete() && fa.delete())
    {
     JOptionPane.showMessageDialog(null, "訊息已成功刪除~~", "Warning", JOptionPane.INFORMATION_MESSAGE);
    }
	  imageIcon = new ImageIcon("");
      picarea = new JLabel("");
	  upPanel.add(picarea,BorderLayout.CENTER);
	  validate();
	  preFileName="";
   }
}


public void runClient()
   {
  try {
		    // Step 1: Create a ServerSocket.
			// 小狐修改，直接在button action的地方就先開好server socket
            //server = new ServerSocket( 65000, 100 );
    while ( true ) {
            // Step 2: Wait for a connection.
            status.append( "Waiting for connection.....\n" );
            connection = server.accept();           
            status.append( "send to : " + connection.getInetAddress().getHostName()+"\n" );

            // Step 3: Get input and output streams.			
			SocketOutput = new ObjectOutputStream(connection.getOutputStream());
		    SocketInput = new ObjectInputStream(connection.getInputStream());
                                                                       
		    // Step 4: Process connection. 
		    while(! connection.isClosed() ) // 判斷Server是否已經切斷connection
			{
 				  do {
					  try {
					  	  message = (String) SocketInput.readObject();
					  	  System.out.println(message);
				   	   }
					   catch ( ClassNotFoundException cnfex ) {
						  System.out.println("Unknown object type received\n" );
				       }
				  } while( !message.equals( "Starting transfering!!" ) );        
				  
              //接收sendaddr(原送件人的地址)
			   try {
					sendaddr = (String) SocketInput.readObject();
					System.out.println("原送件人"+sendaddr);
			   }
			   catch ( ClassNotFoundException cnfex ) {
				    System.out.println("Unknown object type received\n" );
			   }
			  /* 
              //將sendaddr分解，建立資料夾名稱
		        attdir=attdir.valueOf(sendaddr.charAt(addrindex)); 
				addrindex++;
				while(sendaddr.charAt(addrindex)!='@')
	             {
					if(sendaddr.charAt(addrindex)=='<')
                     {
                      attdir=" ";
					  addrindex++;		
					 }
                   attdir+=attdir.valueOf(sendaddr.charAt(addrindex));    
               	   addrindex++;
	             }  
               */
		     //把收到的訊息存在c:\Messages下
			  MessagesDir = new File(rootaddr);
              if(!MessagesDir.exists())
			   {
				    MessagesDir.mkdir();		           
               }
  
			 //寫入的照片檔案名稱為output.jpg(以後可能會編號or....)
               for(int i=1;i>=1;i++)
               {          
			     File msgFile = new File(MessagesDir, i + ".jpg");
                 if(!msgFile.exists())
				 {
  				   Fname =String.valueOf(i) ;
       			   FileOutput = new BufferedOutputStream(new FileOutputStream(msgFile));  
				  	  try{
					      byte[] buffer = new byte[2048];
					      int read_len;					
					         while( (read_len = SocketInput.read(buffer)) >0 )
					           {
						           FileOutput.write(buffer, 0, read_len);
					           }
					       FileOutput.close();
				       } 
					   catch(IOException ie){
					       status.append("cannot write file!\n" + ie);
					   }
				    break;
				   }//end of if
				  else
				    continue;	   				  
				}//end of for

			   //將sendaddr寫入檔案
               File oriaddr = new File( rootaddr,"addr" + Fname + ".txt");
               FileOutputStream fout = new FileOutputStream(oriaddr);
		         try{
	      	          fout.write(sendaddr.getBytes());
                      fout.close();
		         }
		         catch(Exception e) {
                      e.printStackTrace();
                 }			 
		                                                                               
            // Step 5: Close connection.(關閉Socket)
		    status.append("接收完畢.....\n");
			SocketOutput.close();
			SocketInput.close();
            connection.close();
	     }//end of while

      //顯示訊息		 
      int n = JOptionPane.showConfirmDialog(null, "您有新訊息\n現在讀取??",
              "Warning",JOptionPane.YES_NO_OPTION);
      if (n == JOptionPane.YES_OPTION)
	   {
	     readMessage=new showpic();
		 readMessage.startShow(rootaddr+ Fname + ".jpg",rootaddr+"addr"+Fname+".txt");
	   } else if (n == JOptionPane.NO_OPTION) {
          continue;
       } else {
          continue;
       }

	   }//end of while
	  }//end of try
      catch ( EOFException eof ) {
         status.append( "Server terminated connection\n" );
      }
      catch ( IOException io ) {
         io.printStackTrace();
      }
   }//end of runClient()


 public static void main( String args[] )
   {
     MMSClient app=new MMSClient();
	 app.addWindowListener(
		new WindowAdapter(){
		 public void windowClosing(WindowEvent e){
			 System.exit(0);
         }
	    }  
	 );
   }//end of main
}//end of MMSClinet
