/*
 * 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.io.File;
import de.schlichtherle.io.FileWriter;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.*;
/**
 *
 * @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() {
    }
    
    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);
    }
    
    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(500, 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(){
                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(){
                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(){
                public void actionPerformed(ActionEvent event){
                    //User has pressed save
                    WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.FILE, defaultFilePath, WepsFileChooser.SAVE);                    
                    wfc.setAcceptAllFileFilterUsed(true);
                    wfc.setPersitSelectedFile(false);
                    File path = new File(defaultFilePath);
                    if (path.isDirectory()){
                        wfc.setCurrentDirectory(path);
                    }
                    else{
                        wfc.setCurrentDirectory(path.getParentFile());
                        File file = Util.incrementFileName(path);
                        wfc.setSelectedFile(file);
                    }
                    
                    if (wfc.showDialog(wmDialog.dialog, "Save Message") == wfc.APPROVE_OPTION){
                       File logFile = new File(wfc.getSelectedFile());                       
                       try{
                           BufferedWriter out = new BufferedWriter(new FileWriter(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);
    }
    
    public static int showMessageList(Component parent, String title, String text, String defaultFilePath, Vector <WepsMessage> messages){
        return showMessageList(parent, title, text, defaultFilePath, OK_OPTION | SAVE_OPTION, messages);
    }
    
     public static int showMessageList(Component parent, String title, String text, String defaultFilePath, int optionType, Vector <WepsMessage> messages){
        
         WepsMessage.MessageSeverity maxSeverity = WepsMessage.MessageSeverity.INFORMATION;
        
        //Message stuff        
        WepsMessageLog log = new WepsMessageLog(messages);
        Vector <WepsMessage.MessageSeverity> sortedSeverities = log.getSortedSeverites();
        StringBuffer sb = new StringBuffer();
        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);
     }
    
    public static int showMessageList(Component parent, String title, String defaultFilePath, Vector <WepsMessage> messages){
        return showMessageList(parent, title, null, defaultFilePath, messages);

    }
    

}
