package usda.weru.weps;

import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TFileWriter;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.help.CSH;
import org.apache.log4j.Logger;
import usda.weru.util.TextInputDialog;

/**
 * This class/object is used to write notes for the MCREW aboject using a specific "RUN" at the
 * management file level that will be retrieved from the file into the text area provided.
 */
public class NotPanel extends usda.weru.weps.gui.NotPanel_n implements PropertyChangeListener {

    private static final long serialVersionUID = 1L;

    private static final Logger LOGGER = Logger.getLogger(NotPanel.class);
    /**
     * String used to locate the property name for any changes on that property
     * to be reported.
     */
    public static final String WriteNotesFile = "WriteNotesFile";

    /**
     *Default constructor for notes panel
     */
    public NotPanel() {
        addHelp();
    }

    /**
     * Single argument constructor that provides the title strin to go with for the panel.
     * @param sTitle Title string for the notes panel
     */
    public NotPanel(String sTitle) {
        this();
        setTitle(sTitle);
    }

    private void addHelp() {
        CSH.setHelpIDString(JSP_text, "notesPanel_html");
        CSH.setHelpIDString(JTA_text, "notesPanel_html");
    }

    /**
     * Entry point for testing standalone. Used if this dialog is rum as an independent application.
     * If executed, makes the GUI for MAILER visible.
     * @param args These are the command line arguments passed to the main method.
     */
    static public void main(String args[]) {
        NotPanel np = new NotPanel();
        np.setVisible(true);
        RunFileData rfd = new RunFileData();
        rfd.addPropertyChangeListener(np);
        rfd.initialize();
    }

    private String recvText = "";

    /**
     * Recognizes and takes appropriate actions on registered properties from different screens to
     * update and synchronize data and GUI screens as needed.
     * @param e The event itself that is responsible for triggering the change required for registered
     * properties/components.
     */
    @Override
    public void propertyChange(PropertyChangeEvent e) {
        switch (e.getPropertyName()) {
            case RunFileData.NotesText:
                recvText = (String) e.getNewValue();
                JTA_text.setText(recvText.replace('|', '\n'));
                break;
            case WriteNotesFile:
                writeNotesFile((String) e.getNewValue());
                break;
        }
    }

    /**
     *
     * @param event
     */
    @Override
    public void JTAText_focusLost(java.awt.event.FocusEvent event) {
        save();
    }

    private void save() {
        String sendText = JTA_text.getText();
        sendText = sendText.replace('\n', '|');
        changes.firePropertyChange(RunFileData.NotesText, recvText, sendText);
    }

    private final PropertyChangeSupport changes = new PropertyChangeSupport(this);

    /**
     * Allows the container to add or register some other components to recognize the changes that occur
     * on this component.
     * @param l The listener that listens and reacts towards the the changes to be reflected.
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    /**
     * Allows the container to remove or de-register some other components and stop recognizing the
     * changes that occur on this component.
     * @param l The listener that does not listen and react towards the the changes to be reflected.
     */
    @Override
    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }

    /**
     * Writes the notes into the file which can be retieved at a later stage.
     * @param dir The directory location string where the notes file exists.
     */
    public void writeNotesFile(String dir) {
        try (PrintWriter out = new PrintWriter(new BufferedWriter(new TFileWriter(
                new TFile(dir, RunFileData.NotesFileName))))) {
            String notes = JTA_text.getText();
            out.println(notes);
        } catch (FileNotFoundException e) {
            //System.err.println("NP_wNF: " + e);
        }
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JNPClear_actionPerformed(java.awt.event.ActionEvent evt) {
        JTA_text.setText("");
        save();
    }

    /**
     *
     * @param evt
     */
    @Override
    protected void JBEdit_actionPerformed(java.awt.event.ActionEvent evt) {
        String tmp = TextInputDialog.showInputDialog(null, "Notes Editor", JTA_text.getText());
        if (tmp != null) {
            JTA_text.setText(tmp);
            JTA_text.requestFocusInWindow();
            JTA_text.setCaretPosition(0);
            save();
        }
    }
}
