//MMSServer.java
//建立socket把圖片傳至各收端
import java.io.*;
import java.io.BufferedOutputStream.*;
import java.util.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;

public class MMSServer extends TimerTask {
   private File f1 ;  
   private Socket connection;
   String path="",photo="",orimsg="",ip="",sendaddr="";
   int check=0,row;

public void run()
 {
    //連接資料庫
	try {
      Class.forName("org.gjt.mm.mysql.Driver").newInstance();
    }
    catch (Exception E) {
    	System.err.println("Unable to load driver.");
        E.printStackTrace();
    }	
	try {
	//Connection Management 
    	Connection conn =
               DriverManager.getConnection("jdbc:mysql://localhost:3306/MMS_Messages","luckystraw","babyweiwei");
		conn.setAutoCommit(true);
        Statement stmt = conn.createStatement();

    //選取欲讀取的table
	ResultSet sql = stmt.executeQuery("SELECT * FROM message WHERE check=0");
    			
		while (sql.next())
    	{
            //sql.getInt(1)==1表示已傳送過
			if(sql.getInt(1) == 1)
				continue;
			else{
            //印出資料
			//System.out.print("check:"+sql.getInt(1)+"\n");
			//System.out.print("path:"+sql.getString(2)+"\n");
			//System.out.print("photo:"+sql.getString(3)+"\n");
			//System.out.print("msg:"+sql.getString(4)+"\n");
			//System.out.println("ip:"+sql.getString(5)+"\n");
			//System.out.println("sendaddr:"+sql.getString(6)+"\n");
			//System.out.println("row:"+sql.getString(7)+"\n");
			check = sql.getInt(1);			
            path = sql.getString(2);
			photo = sql.getString(3);			
			orimsg = sql.getString(4);			
			ip = sql.getString(5);			
			sendaddr = sql.getString(6);
			row = sql.getInt(7);
			}
		    System.out.println(path+"   "+photo+"   "+orimsg+"   "+"   "+ip+"   "+sendaddr);
		    check = runServer(check, path, photo, orimsg, ip, sendaddr);
			  if(check == 1)
			  {
				String checksql;
			    Statement stmt2 = conn.createStatement();
				checksql="update message set check = 1 where rowid = \""+row+"\"";
                stmt2.execute(checksql);
				continue;
              }
			  else
				continue;
		}

		sql.close();
		conn.close();
		//System.out.print("check:"+check+"\npath:"+path+"\nphoto:"+photo+"\nmsg:"+orimsg+"\nip:"+ip+"\nsendaddr:"+sendaddr+"\n\n");	
	
	}
	catch (SQLException E) {
		//例外處理..錯誤訊息
	    System.out.println("SQLException: " + E.getMessage());
		System.out.println("SQLState:     " + E.getSQLState());
	    System.out.println("VendorError:  " + E.getErrorCode());
	} 
 }//end of run()

   public int runServer(int s0, String s1, String s2, String s3, String s4, String s5)
   {
       check = s0;
	   path = s1;
	   photo = s2;
	   orimsg = s3;
	   ip = s4;
	   sendaddr = s5;

      try {
      // Step 1: Create a Socket to make connection.
          System.out.println( "Attempting connection......");
          connection = new Socket(ip,65000 );
          System.out.println("Connected to : " +
          connection.getInetAddress().getHostName());

      // Step 2: Get the input streams.                                                      
          ObjectInputStream SocketInput = new ObjectInputStream(connection.getInputStream());
		  ObjectOutputStream SocketOutput = new ObjectOutputStream(connection.getOutputStream());
		  String message = "Starting transfering!!";
		  System.out.println( message);        
		  
      // Step 3: Process connection. 		  
		   while(!connection.isClosed())
		   {
			   SocketOutput.writeObject(message);
			   SocketOutput.flush();

			   SocketOutput.writeObject(sendaddr);
			   SocketOutput.flush();

               //設定路徑及檔案名稱          
			    f1= new File(path+photo);
			   System.out.println(path+photo);
			   BufferedInputStream FileInput = new BufferedInputStream(new FileInputStream(f1));//欲傳送的檔案名稱   
			   try
		       {	
				 byte[] buffer = new byte[2048];//讀檔
				 int read_len;		   
					while( (read_len = FileInput.read(buffer) ) > 0) {				 
					  SocketOutput.write(buffer, 0, read_len);
				    }
				  FileInput.close(); 
			   }
			   catch(IOException ie)
			   {
				 System.out.println("file cannot opened\n" + ie);
			   }

              System.out.println("傳送完畢.....\n");     
         
      // Step 4: Close connection.
			SocketOutput.close();
			SocketInput.close();
			   check=1;
            connection.close();
	       } // end of while   
      }//end of try
      catch ( EOFException eof ) {
         System.out.println( "\nClient terminated connection" );
      }
      catch (IOException e) {}
    
      return check;

   }//end of runServer()
  
}//end of MMSServer

