//=================================================================
//                HTMLViewer MenuActionListener
//=================================================================
//
//    This class provides the means for controlling the required
// actions needed to execute the various activities used in the
// HTMLViewer plugin. The events are generated by the Viewer_MenuBar
// & Viewer_ToolBar classes.
//
//                 << MenuActionListener.java >>
//
//=================================================================
// Copyright (C) 2013 Dana M. Proctor.
// Version 1.1 08/04/2013
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version
// 2 of the License, or (at your option) any later version. This
// program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU General Public License for more details. You should
// have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// (http://opensource.org)
//
//=================================================================
// Revision History
// Changes to the code should be documented here and reflected
// in the present version number. Author information should
// also be included with the original copyright author.
//=================================================================
// Version 1.0 07/27/2013 Original HTMLViewer MenuActionListener Class.
//         1.1 08/04/2013 Completed Action Event Processing.
//         
//-----------------------------------------------------------------
//                 danap@dandymadeproductions.com
//=================================================================

package com.dandymadeproductions.htmlviewer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import com.dandymadeproductions.lindyframe.gui.LindyFrame_MenuActionCommands;
import com.dandymadeproductions.lindyframe.utilities.LindyFrame_ResourceBundle;
import com.dandymadeproductions.lindyframe.utilities.LindyFrame_Utils;

/**
 *    The MenuActionListener class provides the means for controlling
 * the required actions needed to execute the various activities used
 * in the HTMLViewer plugin. The events are generated by the Viewer_MenuBar
 * & Viewer_ToolBar classes.
 * 
 * @version 1.1 08/04/2013
 */

class MenuActionListener implements ActionListener
{
   // Class Instances
   //private static final long serialVersionUID = -671737399091365303L;
   
   private JFrame parent;
   private HTMLViewer htmlViewer;
   private String resourceSearchFor, resourceStringNotFound;
   private String resourceFound, resourceMatches;
   private String resourceTitleAlert, resourceErrorFile;
   private String lastOpenDirectory;
   
   //==============================================================
   // MenuActionListener Constructor.
   //==============================================================

   public MenuActionListener(JFrame mainFrame, HTMLViewer viewer, LindyFrame_ResourceBundle resourceBundle)
   {
      parent = mainFrame;
      htmlViewer = viewer;

      lastOpenDirectory = "";
      
      resourceSearchFor = resourceBundle.getResourceString("MenuActionListener.label.SearchFor",
                                                           "Search For");
      resourceStringNotFound = resourceBundle.getResourceString("MenuActionListener.label.StringNotFound",
                                                                "String Not Found");
      resourceFound = resourceBundle.getResourceString("MenuActionListener.label.Found", "Found");
      resourceMatches = resourceBundle.getResourceString("MenuActionListener.label.Matches", "Matches");
      resourceTitleAlert = resourceBundle.getResourceString("MenuActionListener.dialogtitle.Alert",
      "Alert");
      resourceErrorFile = resourceBundle.getResourceString("MenuActionListener.dialogmessage.FileNOTFound",
                                                           "File NOT Found");    
   }

   // ==============================================================
   // ActionEvent Listener method for detecting the inputs from the
   // application and directing to the appropriate routine.
   // ==============================================================

   public void actionPerformed(ActionEvent evt)
   {
      // Setting up some needed instance variables.
      String actionCommand;
      Object item;

      // Initializing
      item = evt.getSource();

      if (item instanceof JMenuItem)
         actionCommand = ((JMenuItem) item).getActionCommand();
      else if (item instanceof JButton)
         actionCommand = ((JButton) item).getActionCommand();
      else
         actionCommand = "";
      // System.out.println(actionCommand);

      // Directing Appropriate Actions.

      // =============================
      // File Actions

      // Open
      if (actionCommand.equals(Viewer_MenuBar.ACTION_FILE_OPEN))
      {
         openAction(parent);
         return;
      }

      // Exit (This one caught by lindyFrame.)
      if (actionCommand.equals(LindyFrame_MenuActionCommands.ACTION_EXIT))
      {
         // System.out.println("File Exit");
         return;
      }
      
      // =============================
      // Edit Actions
      
      // Search
      if (actionCommand.equals(Viewer_MenuBar.ACTION_EDIT_SEARCH))
      {
         searchAction(parent);
         return;
      }
   }

   //==============================================================
   // Class Method to open a HTML file for viewing.
   //==============================================================

   private void openAction(JFrame parent)
   {
      // Method Instances.
      JFileChooser htmlFileChooser;
      String fileName;

      // Choosing the directory to import data from.
      if (lastOpenDirectory.equals(""))
         htmlFileChooser = new JFileChooser();
      else
         htmlFileChooser = new JFileChooser(new File(lastOpenDirectory));

      // Add a FileFilter for *.html and open dialog.
      htmlFileChooser.setFileFilter(new FileFilter()
      {
         public boolean accept(File file)
         {
            String extension, fileName;
            int lastIndexOfDot;
            
            // All Directories
            if (file.isDirectory())
               return true;
            
            // Only, *.html
            extension = "";
            fileName = file.getName();
            lastIndexOfDot = fileName.lastIndexOf('.');

            if (lastIndexOfDot > 0 &&  lastIndexOfDot < fileName.length() - 1)
                extension = fileName.substring(lastIndexOfDot + 1).toLowerCase();
            
            if (extension.equals("html"))
               return true;
            
            // Nope.
            return false;
          }
         public String getDescription()
         {
            return "HTML Files";
         } 
      });

      int result = htmlFileChooser.showOpenDialog(parent);

      // Looks like might be good so lets check and read data.
      if (result == JFileChooser.APPROVE_OPTION)
      {
         // Save the selected directory so can be used again.
         lastOpenDirectory = htmlFileChooser.getCurrentDirectory().toString();

         // Collect file name.
         fileName = htmlFileChooser.getSelectedFile().getName();
         fileName = htmlFileChooser.getCurrentDirectory() + LindyFrame_Utils.getFileSeparator() + fileName;

         // Try Loading the file.
         if (!fileName.equals(""))
            htmlViewer.loadPage("file:" + fileName);
         else
         {
            JOptionPane.showMessageDialog(null, resourceErrorFile, resourceTitleAlert,
                                          JOptionPane.ERROR_MESSAGE);
         }
      }
   }
   
   //==============================================================
   // Class Method to search the current opened HTML document
   // for the given key word.
   //==============================================================

   private void searchAction(JFrame parent)
   {
      // Method Instances
      String searchWord;
      int foundWord;
      
      searchWord = JOptionPane.showInputDialog(parent, resourceSearchFor + " :");
      foundWord = htmlViewer.viewerPane.search(searchWord);
      
      if(foundWord > 0)
         htmlViewer.setStatus(resourceFound + " " + foundWord + " " + resourceMatches, -1, 3);
      else
         htmlViewer.setStatus(resourceStringNotFound, -1, 3);
   }
}