/*
 * WepsMessageDialog.java
 *
 * Created on January 17, 2006, 4:31 PM
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */
package usda.weru.util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import de.schlichtherle.truezip.file.TFile;
import de.schlichtherle.truezip.file.TFileWriter;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.*;
import usda.weru.util.wepsFileChooser2.WepsFileChooser2;
import usda.weru.util.wepsFileChooser2.WepsFileTypes2;

/**
 *
 * @author joelevin
 */
public class WepsMessageDialog {

    /**
     *
     */
    public static final int OK_OPTION = 1;

    /**
     *
     */
    public static final int SAVE_OPTION = 2;

    /**
     *
     */
    public static final int CANCEL_OPTION = 4;

    private static int result = CANCEL_OPTION;
    private static String text = "";
    /** Creates a new instance of WepsMessageDialog */
    protected JDialog dialog;

    /**
     *
     */
    public WepsMessageDialog() {
    }

    /**
     *
     * @param parent
     * @param title
     * @param message
     * @param defaultFilePath
     * @return
     */
    public static int showScrollableMessage(Component parent, String title, String message, String defaultFilePath) {
        return showScrollableMessage(parent, title, message, defaultFilePath, JOptionPane.INFORMATION_MESSAGE, OK_OPTION | SAVE_OPTION);
    }

    /**
     *
     * @param parent
     * @param title
     * @param message
     * @param defaultFilePath
     * @param messageType
     * @param optionType
     * @return
     */
    public static int showScrollableMessage(Component parent, String title, String message, final String defaultFilePath, int messageType, int optionType) {
        final WepsMessageDialog wmDialog = new WepsMessageDialog();
        //Scroll pane and text area
        text = message;
        JTextArea JTA_text = new JTextArea(message);
        JTA_text.setEditable(false);
        JScrollPane JP_scroll = new JScrollPane(JTA_text, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        JP_scroll.setPreferredSize(new Dimension(750, 200));

        //optionpane options        
        JOptionPane option = new JOptionPane();
        option.setMessageType(messageType);
        ArrayList<JButton> options = new ArrayList<JButton>();

        if (bitCheck(optionType, OK_OPTION)) {
            JButton temp = new JButton("Ok");
            temp.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    //User has pressed okay
                    result = OK_OPTION;
                    wmDialog.dialog.dispose();
                }
            });
            options.add(temp);
        }

        if (bitCheck(optionType, CANCEL_OPTION)) {
            JButton temp = new JButton("Cancel");
            temp.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    //User has pressed cancel
                    result = CANCEL_OPTION;
                    wmDialog.dialog.dispose();
                }
            });
            options.add(temp);
        }

        if (bitCheck(optionType, SAVE_OPTION)) {
            JButton temp = new JButton("Save");
            temp.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    //User has pressed save
                    WepsFileChooser2 wfc = new WepsFileChooser2(WepsFileTypes2.File, defaultFilePath, WepsFileChooser2.Action.Save);
                    wfc.setAcceptAllFileFilterUsed(true);
                    wfc.setPersistSelectedFile(false);
                    TFile path = new TFile(defaultFilePath);
                    if (path.isDirectory()) {
                        wfc.setCurrentDirectory(path.getAbsolutePath());
                    } else {
                        wfc.setCurrentDirectory(path.getParentFile().getAbsolutePath());
                        TFile file = Util.incrementFileName(path);
                        wfc.setSelectedFile(file);
                    }
                    wfc.setApproveButtonText(WepsFileChooser2.ApproveText.SAVE);

                    if (wfc.showDialog(wmDialog.dialog) == WepsFileChooser2.APPROVE_OPTION) {
                        TFile logFile = new TFile(wfc.getSelectedFile());
                        try {
                            BufferedWriter out = new BufferedWriter(new TFileWriter(logFile));
                            out.write(new Date().toString());
                            out.write(System.getProperty("line.separator"));
                            out.write(text);
                            out.close();
                        } catch (IOException ioe) {
                            JOptionPane.showMessageDialog(wmDialog.dialog, ioe.toString(), "Save Error,", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }
                }
            });
            options.add(temp);
        }

        option.setOptions(options.toArray());

        option.setMessage(JP_scroll);

        //Dialog options   
        wmDialog.dialog = option.createDialog(parent, title);
        wmDialog.dialog.setResizable(true);
        try {
            wmDialog.dialog.setAlwaysOnTop(true);
        } catch (SecurityException se) {
        }//Okay nevermind, we didn't really want to be on top.
        wmDialog.dialog.setVisible(true);

        //This won't return until the dialog is disposed of by an action event.
        return result;
    }

    private static boolean bitCheck(int flags, int bit) {
        return ((flags & bit) == bit);
    }

    /**
     *
     * @param parent
     * @param title
     * @param text
     * @param defaultFilePath
     * @param messages
     * @return
     */
    public static int showMessageList(Component parent, String title, String text, String defaultFilePath, ArrayList<WepsMessage> messages) {
        return showMessageList(parent, title, text, defaultFilePath, OK_OPTION | SAVE_OPTION, messages);
    }

    /**
     *
     * @param parent
     * @param title
     * @param text
     * @param defaultFilePath
     * @param optionType
     * @param messages
     * @return
     */
    public static int showMessageList(Component parent, String title, String text, String defaultFilePath, int optionType, ArrayList<WepsMessage> messages) {

        WepsMessage.MessageSeverity maxSeverity = WepsMessage.MessageSeverity.INFORMATION;

        //Message stuff        
        WepsMessageLog log = new WepsMessageLog(messages);
        ArrayList<WepsMessage.MessageSeverity> sortedSeverities = log.getSortedSeverites();
        StringBuilder sb = new StringBuilder();
        for (WepsMessage.MessageSeverity severity : sortedSeverities) {
            //Determine if this severity is worse
            if (severity.isMoreSevereThan(maxSeverity)) {
                maxSeverity = severity;
            }
            sb.append("[ " + severity.toString() + " ]\n");
            for (WepsMessage message : log.getMessages(false, severity)) {
                sb.append(message.getMessage() + "\n");
            }
            sb.append("\n");
        }
        int type = 0;
        switch (maxSeverity) {
            case INFORMATION:
                type = JOptionPane.INFORMATION_MESSAGE;
                break;
            case WARNING:
                type = JOptionPane.WARNING_MESSAGE;
                break;
            case ERROR:
                type = JOptionPane.ERROR_MESSAGE;
                break;
        }
        if (text != null && text.length() > 0) {
            text = text + "\n" + sb.toString();
        } else {
            text = sb.toString();
        }
        return showScrollableMessage(parent, title, text, defaultFilePath, type, optionType);
    }

    /**
     *
     * @param parent
     * @param title
     * @param defaultFilePath
     * @param messages
     * @return
     */
    public static int showMessageList(Component parent, String title, String defaultFilePath, ArrayList<WepsMessage> messages) {
        return showMessageList(parent, title, null, defaultFilePath, messages);

    }

}
