package usda.weru.erosion;

import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TFileOutputStream;
import javax.swing.*;
import java.util.*;
import java.util.zip.*;
import java.beans.*;
import java.io.IOException;
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 static final long serialVersionUID = 1L;

    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);
    }

    /**
     *
     * @param event
     */
    @Override
    public void JBSend_ActionPerformed(java.awt.event.ActionEvent event) {
        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<TFile> attachments = null;
        String attachment = JTF_attachment.getText().trim();
        if (attachment == null) {
        } else if (attachment.trim().length() == 0) {
        } else if (!(new TFile(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 TFile(attachment).getName();
            String parent = new TFile(attachment).getParent();
            filename = filename.substring(0, filename.lastIndexOf('.'));

            TFile zipFile = new TFile(parent, filename + "z.zip");

            try {

                TFileOutputStream os = new TFileOutputStream(zipFile);
                ZipOutputStream zip_os = new ZipOutputStream(os);
                Util.writeFileToZip(zip_os, new TFile(parent, "stderr.txt"), filename);
                Util.writeFileToZip(zip_os, new TFile(parent, "stdout.txt"), filename);
                Util.writeDirToZip(zip_os, new TFile(parent), filename, new ZipFileFilter(filename));

                zip_os.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
            attachments = new Vector<TFile>();
            attachments.add(zipFile);
        }

        try {
            Mailer.sendMail(mailHost,
                    sentFrom, sendTo, subject, messageText,
                    attachments);
        } catch (java.io.IOException | javax.mail.internet.AddressException e) {
            JOptionPane.showMessageDialog(this, e,
                    "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) {
        }
    }

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

    }

    /**
     *
     * @param event
     */
    @Override
    public void JBRun_ActionPerformed(java.awt.event.ActionEvent event) {

        WepsFileChooser wpc = new WepsFileChooser(WepsFileChooser.Filetype.SWEEP, runPath,
                WepsFileChooser.SELECT);
        wpc.setCurrentDirectory(new TFile((new TFile(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;
        }

        @Override
        public boolean accept(java.io.File dir, String name) {
            if ((new TFile(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.
     */
    @Override
    public void propertyChange(PropertyChangeEvent e) {
        switch (e.getPropertyName()) {
            case ConfigData.EmailSender:
                JTF_from.setText(e.getNewValue().toString());
                break;
            case ConfigData.MailHost:
                mailHost = e.getNewValue().toString();
                break;
            case ConfigData.SWEEPWorkDir:
                runPath = e.getNewValue().toString();
                break;
            case ConfigData.CommentAddr:
                JCB_to.addItem(e.getNewValue());
                break;
            case ConfigData.BugsAddr:
                JCB_to.addItem(e.getNewValue());
                break;
        }
    }

}
