package usda.weru.erosion;

import de.schlichtherle.io.File;
import de.schlichtherle.io.FileOutputStream;
import javax.swing.*;
import java.util.*;
import java.util.zip.*;
import java.beans.*;
import javax.help.*;
import usda.weru.util.*;


/**
 * This class/object is used to send emails with bug reports attached or interface mis behaviour
 * messages to the WEPS support team from within the interface. Project folders and run files with
 * particular test case could be used as information.
 */
public class Email extends usda.weru.erosion.gui.Email_n implements PropertyChangeListener
{

	private String mailHost;
	private String runPath;
    
	/**
	 * Default constructor for the email object/class tbat calls the parent GUI object and adds help
	 * material for the GUI.
	 */
	public Email()
	{
		super();
		addHelp();
		//setIconImage(wepsbIcon.getImage());
		JP_main.setVisible(true);
	}

    /**
	 *  Single argument constructor for the email object/class tbat calls the parent GUI object and adds
	 *  help material for the GUI.
	 * @param sTitle The title string for the parent dialog box in which the email GUI sits.
	 */
	public Email(String sTitle)
	{
		this();
		setTitle(sTitle);
                 //Setting the Icon Image in the title bar
		super.setIconImage(About.getWeruIconImage());
	}

	
	/**
 * help stuff
 */
	
    private void addHelp()
    {
        
        CSH.setHelpIDString(JLabel1, "emailTo_html");
//        CSH.setHelpIDString(JTF_to, "emailTo_html");
        CSH.setHelpIDString(JLabel2, "emailFrom_html");
        CSH.setHelpIDString(JTF_from, "emailFrom_html");
        CSH.setHelpIDString(JLabel3, "emailSubject_html");
        CSH.setHelpIDString(JTF_subject, "emailSubject_html");
        CSH.setHelpIDString(JLabel4, "emailAttachment_html");
        CSH.setHelpIDString(JTF_attachment, "emailAttachment_html");
        
        CSH.setHelpIDString(JSP_text, "emailComments_html");
        CSH.setHelpIDString(JP_buttons, "emailButtons_html");
        CSH.setHelpIDString(JP_main, "emailScreen_html");

        
        /*CSH.setHelpIDString(JB_send, "emailSendButton");
        CSH.setHelpIDString(JB_cancel, "emailCancelButton");
        CSH.setHelpIDString(JB_Run, "emailAttachRunButton");
        CSH.setHelpIDString(JB_Project, "emailAttachProjButton");*/
          
    }

	/**
	 *  Four argument constructor for the email object/class tbat calls the parent GUI object and adds
	 * help material for the GUI.
	 * @param sTitle The title string for the parent dialog box in which the email GUI sits.
	 * @param runDir Indicates the system path where all the run files sit.
	 * @param cd The config data class where any changes made here need to be propagated for updation.
	 */
	public Email(String sTitle, String runDir, ConfigData cd)
	{
		this();
//		bugFlg = true;		
		cd.fireAll(this);		
		setTitle(sTitle);
                 //Setting the Icon Image in the title bar
                super.setIconImage(About.getWeruIconImage());
                
		JTF_attachment.setText(runDir);
	}

	/**
	 * This method notifies when the window or frame is resized and the components need to be re-arranged 
	 * so they are evenly spaced relative to each other.
	 * @param args Command line arguments passed that are needed if it were a stand alone application.
	 */
	static public void main(String args[])
	{
		//(new Email()).setVisible(true);
                (new Email()).setVisible(true);
	}


	public void JBSend_ActionPerformed(java.awt.event.ActionEvent event)
	{
		// to do: code goes here.

//		String sendTo = JTF_to.getText();
		String sendTo = (String) JCB_to.getSelectedItem();
		if (sendTo.length() == 0) {
			//System.err.println("no recipient");
			return;
		}
		String sentFrom = JTF_from.getText();
		if (sentFrom.length() == 0) {
			//System.err.println("no sender");
			return;
		}

		String subject = JTF_subject.getText();
		if (subject.length() == 0) {
			subject = JTF_attachment.getText().trim();
		}
		
		String messageText = JTA_text.getText();
		if (messageText.length() == 0) {
			messageText = "no message";
		}

		Vector attachments = null;
		String attachment = JTF_attachment.getText().trim();
		if (attachment == null) {}
		else if (attachment.trim().length() == 0) {}
		else if (!(new File(attachment).exists())) {
			JOptionPane.showMessageDialog(this,
										  "Attachment not found -- aborting send",
										  "Error (E-001)",
										  JOptionPane.WARNING_MESSAGE);
			return;
		} else {
            //String filename = attachment.substring( attachment.lastIndexOf('\\'), attachment.lastIndexOf('.') );
            String filename = new File(attachment).getName();
			String parent = new File(attachment).getParent();
            filename = filename.substring(0, filename.lastIndexOf('.') );
             
			File zipFile = new File(parent, filename + "z.zip");
			
			try {
                
				FileOutputStream os = new FileOutputStream(zipFile);
				ZipOutputStream zip_os = new ZipOutputStream(os);
				Util.writeFileToZip(zip_os, new File(parent, "stderr.txt"), filename);
				Util.writeFileToZip(zip_os, new File(parent, "stdout.txt"), filename);
				Util.writeDirToZip(zip_os, new File(parent), filename, new ZipFileFilter(filename));
                
				zip_os.close();
                
			} catch (Exception e) {
				e.printStackTrace();
			}
			attachments = new Vector();
			attachments.add(zipFile);
		}

		try {
			Mailer.sendMail(mailHost,
							sentFrom, sendTo, subject, messageText,
							attachments);
		} catch (java.io.IOException e) {
			JOptionPane.showMessageDialog(this, e,
										  "Error -- Mail not sent",
										  JOptionPane.WARNING_MESSAGE);
			return;
		} catch (javax.mail.internet.AddressException f) {
			JOptionPane.showMessageDialog(this, f,
										  "Error -- Mail not sent",
										  JOptionPane.WARNING_MESSAGE);
			return;
		} catch (javax.mail.MessagingException g) {
			JOptionPane.showMessageDialog(this, g,
										  "Error -- Mail not sent",
										  JOptionPane.WARNING_MESSAGE);
		}

		try {
			this.setVisible(false);
		} catch (java.lang.Exception e) {
		}
	}

	public void JBCancel_ActionPerformed(java.awt.event.ActionEvent event)
	{
		try {
			this.setVisible(false);
		} catch (java.lang.Exception e) {
		}
			 
	}

	public void JBRun_ActionPerformed(java.awt.event.ActionEvent event)
	{

		WepsFileChooser wpc = new WepsFileChooser(WepsFileChooser.SWEEP,runPath,
				WepsFileChooser.SELECT);
		wpc.setCurrentDirectory(new de.schlichtherle.io.File((new de.schlichtherle.io.File(runPath)).getPath()));
		//set the tooltip of "home" button to "Home" instead of "Desktop"
		wpc.homeToolTip(wpc);  
		//remove the NewFolder button
		wpc.disableNewFolder(wpc);

		if (wpc.showDialog(this) == JFileChooser.APPROVE_OPTION) {
			JTF_attachment.setText(wpc.getSelectedFile().getPath());
		}
	}

	private static class ZipFileFilter implements java.io.FilenameFilter {
		String fileName;

		ZipFileFilter(String fileName) {
			this.fileName = fileName;
		}
		
		public boolean accept(java.io.File dir, String name) {
			if ((new File(dir, name)).isDirectory()) return false;
			return name.startsWith(fileName + ".");
		}
	}
    
    /**
	 * The method that gets called when any changes to the registered property happen 
         * whose new vales need to be propagaed and updated so as to reflect the most current data.
	 * @param e The event that occurs on the property.
	 */

	public void propertyChange(PropertyChangeEvent e) {
		if (e.getPropertyName().equals(ConfigData.EmailSender)) {
			JTF_from.setText(e.getNewValue().toString());
		} else if (e.getPropertyName().equals(ConfigData.MailHost)) {
			mailHost = e.getNewValue().toString();
		} else if (e.getPropertyName().equals(ConfigData.SWEEPWorkDir)) {
			runPath = e.getNewValue().toString();
		} else if (e.getPropertyName().equals(ConfigData.CommentAddr)) {
			JCB_to.addItem(e.getNewValue());
		} else if (e.getPropertyName().equals(ConfigData.BugsAddr)) {
			JCB_to.addItem(e.getNewValue());
		}
	}

}
