package org.greenstone.gatherer.feedback;

import java.util.Properties;
import java.net.*;
import java.io.*;
import java.util.Locale;
import java.util.ResourceBundle;
import java.text.MessageFormat;
import javax.swing.*;
import java.awt.Dimension;

/**
 * This class will send the 2 jar files to the server using HTTP Post.
 */
public class SendHTTP
{
    /**
     * This is variable will hold the arguments provided by user in order to send 
     */
    private String[] argument;
    /**
     * This variable will hold the resource of the words that is stored in Messages.properties file.
     * The calling using messages.getString(someString) will caused someString to be translated
     * into some other string that is hold in that file.usually it will caused it to be translated
     * to the language that the user use or choose to have as stated in Locale.
     */
    private static ResourceBundle msg;
    /**
     * This variable will hold the jar file unique code.
     * For example: Jar123File.jar then file_code = 123
     */
    private String file_code;
    /**
     * This is the flag that will say whether or not the sending is successful.
     * If failed = false means its succesful otherwise its failed.
     */
    private boolean failed = false;

    /**
     * Crates instance of SendHTTP
     */
    public SendHTTP () {}
  
    /**
     * This method will send 2 files back to the server.
     * It will also send  the code if the sending is failed then it will give user a message saying whats
     * the possible error of it, and it will make the jar file changed into
     * Unsend_Jar123File.jar file.
     * If the sending is succesful then it will try to send all the other jar files
     * that were failed to send before.And then it will deletes all the jar files
     * that are send successfully.
     * @param args the argument provided to send the email.
     * @param messages hold the resource of the words that is stored in Messages.properties file.
     * @param code the code of the email to be send.
     */
    public void  sendMail(String[] args,ResourceBundle messages,String code) 
    {
	argument = args;
	msg = messages;
	file_code = code;

	try
	    {
		String BND = "---------------------------7d021a37605f0";
		String hostURL =  "http://kanuka.cs.waikato.ac.nz:8090/glifeedback/Upload";

		URL mURL = new URL(hostURL+"?name=posting");
		URLConnection conn = mURL.openConnection();
		
		if (conn instanceof HttpURLConnection)
		    ((HttpURLConnection) conn).setRequestMethod("POST");
		 
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setDefaultUseCaches(false);
		conn.setRequestProperty("Accept","*/*");
		conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BND);
		conn.setRequestProperty("Connection","Keep-Alive");
		conn.setRequestProperty("Cache-Control","no-cache");

		DataOutputStream out;
		out = new DataOutputStream(conn.getOutputStream());

		//--- Sending subject -------
		String txt;
		txt = "--" + BND + "\r\n";
		out.writeBytes(txt);

		txt = "Content-Disposition: form-data; ";
		out.writeBytes(txt);

		String subject;
		subject = "Send Feedback" + code;
		txt = "name=\"" + "Subject" + "\"\r\n"; 
		out.writeBytes(txt);
		
		txt = "\r\n";
		out.writeBytes(txt);

		txt = subject + "\r\n";
		out.writeBytes(txt);
		
		out.flush();

		//--- Sending text ------
		txt = "--" + BND + "\r\n";
		out.writeBytes(txt);

		txt = "Content-Disposition: form-data; ";
		out.writeBytes(txt);

		String attmnt;
		attmnt = "We have succesfully received your feedback report.\n" +
		    "To check what files we have received go to this link: " + hostURL +
		    "/?name=" + code + "\n" + 
		    "Please keep referencing to this ID Code for this feedback report.\n" +
		    "ID Code: " + code;

		txt = "name=\"" + "Text" + "\"\r\n";
		out.writeBytes(txt);
		
		txt = "\r\n";
		out.writeBytes(txt);
		
		txt = attmnt + "\r\n";
		out.writeBytes(txt);

		out.flush();

		//--------- Sending xml-jar file
		FileInputStream fis;
		File f;
		String name,path;
		
		f = new File(args[1]);
		
		txt = "--" + BND + "\r\n";
		out.writeBytes(txt);

		txt = "Content-Disposition: form-data; ";
		out.writeBytes(txt);
		
		name = f.getName();
		txt = "name=\"" + name + "\"; ";
		out.writeBytes(txt);
		
		path = f.getAbsolutePath();
		txt = "filename=\"" + path + "\"\r\n";
		out.writeBytes(txt);

		txt = "Content-Type: aplication/octet-stream\r\n";
		out.writeBytes(txt);

		txt = "\r\n";
		out.writeBytes(txt);

		fis = new FileInputStream(f);
		byte[] data = new byte[1024];		
		int r = 0;
		while((r = fis.read(data, 0, data.length)) != -1) 
		    {			
			out.write(data, 0, r);		
		    }
		fis.close();

		txt = "\r\n";
		out.writeBytes(txt);

		out.flush();

		//--- Sending parser.jar ----
		txt = "--" + BND + "\r\n";
		out.writeBytes(txt);
		
		txt = "Content-Disposition: form-data; ";
		out.writeBytes(txt);
		
		f = new File(args[4]);
		
		name = f.getName();
		txt = "name=\"" + name + "\"; ";
		out.writeBytes(txt);
		
		path = f.getAbsolutePath();
		txt = "filename=\"" + path + "\"\r\n";
		out.writeBytes(txt);

		txt = "Content-Type: application/octet-stream\r\n";
		out.writeBytes(txt);

		txt = "\r\n";
		out.writeBytes(txt);

		fis = new FileInputStream(f);
	        data = new byte[1024];		
		r = 0;
		while((r = fis.read(data, 0, data.length)) != -1) 
		    {			
			out.write(data, 0, r);		
		    }
		fis.close();
		
		txt = "\r\n";
		out.writeBytes(txt);

		out.flush();

		//----- finished sending -----
		txt = "--" + BND + "--";
		out.writeBytes(txt);

		out.flush();
		out.close();

		//----- getting the response ------
		BufferedReader reader;
		reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String responseLine;
		responseLine = null;

		StringBuffer response;
		response = new StringBuffer();
		while ((responseLine = reader.readLine()) != null)
		    response.append(responseLine+"\n");

		reader.close();
	 

		//------ our application's response to server's response
		/*if (response.equals("failed"))
		    {
			failed = true;
		
			JOptionPane.showMessageDialog(null,messages.getString("InternalError")+ "\n" + 
						      messages.getString("Emaillater"),messages.getString("Error"),
						      JOptionPane.ERROR_MESSAGE);
			//Conformation.setFinish(true);
		    }
		else if (response.equals("success"))
		    failed = false;
		else
		{*/
			failed = false;
			JDialog.setDefaultLookAndFeelDecorated(false);
			JDialog dlg = new JDialog();
			JLabel lbl = new JLabel (response.toString());
			
			dlg.getContentPane().add(lbl);
			dlg.pack();
			dlg.setVisible(true);
			// }

		//Conformation.setFinish(true);
	    }
	catch (MalformedURLException exp) 
	    {
		failed = true;
		
		JOptionPane.showMessageDialog(null,"malformed URL" + "\n" + 
					      messages.getString("Emaillater"),messages.getString("Error"),
					      JOptionPane.ERROR_MESSAGE); 
		System.out.println("malformed URL"); 
	    }
	catch (IOException e) 
	    { 
		failed = true;
		
		JOptionPane.showMessageDialog(null,messages.getString("InternalError")+ "\n" + 
					      messages.getString("Emaillater"),messages.getString("Error"),
					      JOptionPane.ERROR_MESSAGE);e.printStackTrace();
	    }

	String dirname;
	dirname = "xmlfeedback/";
	
	if (failed == false)
	    {
		File f;
		f = new File(dirname + "Jar" + file_code + "File.jar");
		f.delete();
		
		File file;
		file = new File(dirname + ".");
		File[] fileList;
		fileList = file.listFiles();
		
		int y;
		for (y = 0 ; y < fileList.length ; y++)
		    {
			String filename;
			filename = isRightJarFile(fileList[y]);
			if (filename != null)
			    {
				renameTo(fileList[y],new File(filename));
				argument[1] = filename;
				sendMail(argument,msg,getCode(filename));
			    }
		    }
	    }
	else
	    {
		File f2;
		f2 = new File(dirname + "Jar" + file_code + "File.jar");
		renameTo(f2,new File(dirname + "Unsend_Jar" + file_code + "File.jar"));
	    }
	
    }
    
    /**
     * This method will rename file.
     * @param src is the name of the file to be renamed.
     * @param dest is the desired file name.
     */
    private void renameTo (File src, File dest)
    {
	if (src.renameTo(dest) == false)
	    {
		try
		    {
			FileInputStream in;
			in = new FileInputStream(src);
			FileOutputStream out;
			out = new FileOutputStream(dest);
			int next;
			
			while (true)
			    {
				next = in.read();
				if (next == -1)
				    break;
				else
				    out.write((byte) next);
			    }
			
			in.close();
			out.close();
		    }
		catch (IOException exp) {exp.printStackTrace();}
	    }
    }

    /**
     * This method will get the extension of the file.
     * @param f is the file that we want to get the extension.
     * @return  the file extension
     */
    private String getExtension(File f)
    {
	String ext;
	ext = null;
	String s;
	s = f.getName();
	int i;
	i = s.lastIndexOf('.');
	
	if (i > 0 &&  i < s.length() - 1)
	    {
		ext = s.substring(i+1).toLowerCase();
	    }
	return ext;
    }
    
    /**
     * This method will get all the name of the file after "_" if the file its a jar file.
     * For example Unsend_Jar123File.jar then this method will return Jar123File, otherwise
     * file with any other format will return null.
     * @param f is the file that we want to get the name.
     */
    private String isRightJarFile(File f)
    {
	String ext;
	ext = null;
	
	if (f.isDirectory() == true)
	    return null;
	
	if (getExtension(f).compareTo("jar") == 0)
	    {
		String s;
		s = f.getName();
		int i;
		i = s.lastIndexOf("_");

		if (i > 0 &&  i < s.length() - 1)
		    {
			ext = s.substring(i+1,s.length());
		    }
		else
		    ext = null;
		
		return ext;
	    }
	else
	    return null;
    }
    
    /**
     * This method will getting the code that inside the Jar filename.
     * For example Jar123File then this method will return 123. 
     */
    private String getCode (String s)
	{
	    int i;
	    i = s.lastIndexOf("Jar");
	    int j;
	    j = s.indexOf("File");
	    String code;
	    code = s.substring((i+3),j);
	    return code;
	}
}









