/*
 * jNPad v0.3 - jNPad's an Simple Text Editor written in Java
 *
 * Copyright (C) 2014-2017  rgs
 *
 * Require JDK 1.6 (or later)
 *
 * 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.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 *
 * Info, Questions, Suggestions & Bugs Report to rgsevero@gmail.com
 */

package jnpad.search;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import jnpad.GUIUtilities;
import jnpad.JNPadFrame;
import jnpad.config.Config;
import jnpad.config.Configurable;
import jnpad.ui.JNPadTreeCellRenderer;
import jnpad.ui.TitledLabel;
import jnpad.ui.plaf.LAFUtils;
import jnpad.ui.status.StatusDisplayable.StatusType;

/**
 * The Class FindResultsPanel.
 *
 * @version 0.3
 * @since   jNPad v0.1
 */
public class FindResultsPanel extends JPanel implements Configurable {
  
  /** The popup menu. */
  JPopupMenu                    popupMenu        = new JPopupMenu();
  
  /** The mi clear. */
  JMenuItem                     miClear          = new JMenuItem(SearchBundle.getString("FindResultsPanel.clear")); //$NON-NLS-1$
  
  /** The mi clear and close. */
  JMenuItem                     miClearAndClose  = new JMenuItem(SearchBundle.getString("FindResultsPanel.clearAndClose")); //$NON-NLS-1$
  
  /** The mi close. */
  JMenuItem                     miClose          = new JMenuItem(SearchBundle.getString("FindResultsPanel.close")); //$NON-NLS-1$

  /** The titled label. */
  TitledLabel                   titledLabel      = new TitledLabel(TitledLabel.ACTION_CLOSE);
  
  /** The scroll pane. */
  JScrollPane                   scrollPane       = new JScrollPane();

  /** The tree. */
  JTree                         tree             = new JTree() {
    private static final long serialVersionUID = 7675171551634139805L;

    @Override 
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      try {
        if (!hasResults()) {
          Font font = getFont();

          g.setColor(getBackground());
          g.fillRect(0, 0, getWidth(), getHeight());

          g.setColor(getForeground());
          g.setFont(font);
          String s = SearchBundle.getString("FindResultsPanel.noResults"); //$NON-NLS-1$
          int j = getFontMetrics(font).stringWidth(s);
          g.drawString(s, getWidth() / 2 - j / 2, getHeight() / 2 + getFont().getSize() / 2);
        }
      }
      catch(Exception ex) {
        //ignored
      }
    }
  };

  /** The target. */
  DefaultMutableTreeNode        target;
  
  /** The root. */
  DefaultMutableTreeNode        root             = new DefaultMutableTreeNode("root", true);                               //$NON-NLS-1$
  
  /** The tree model. */
  DefaultTreeModel              treeModel        = new DefaultTreeModel(root);

  /** The tcr. */
  private JNPadTreeCellRenderer tcr;

  /** The j n pad. */
  private JNPadFrame            jNPad;

  /** Logger. */
  private final static Logger   LOGGER           = Logger.getLogger(FindResultsPanel.class.getName());

  /** UID. */
  private static final long     serialVersionUID = -228723987349195871L;

  /**
   * Instantiates a new find results panel.
   *
   * @param jNPad JNPadFrame
   */
  public FindResultsPanel(JNPadFrame jNPad) {
    super(new BorderLayout());
    try {
      this.jNPad = jNPad;

      jbInit();
    }
    catch (Exception ex) {
      LOGGER.log(Level.WARNING, ex.getMessage(), ex);
      jNPad.setStatus(StatusType.ERROR, ex.getMessage());
    }
  }

  /**
   * Component initialization.
   *
   * @throws Exception the exception
   */
  private void jbInit() throws Exception {
    add(titledLabel, BorderLayout.NORTH);
    add(scrollPane, BorderLayout.CENTER);
    scrollPane.getViewport().add(tree, null);

    titledLabel.setTitle(SearchBundle.getString("FindResultsPanel.titledLabel")); //$NON-NLS-1$

    tree.setModel(treeModel);
    tree.setScrollsOnExpand(true);
    tree.setRootVisible(false);
    tree.expandPath(new TreePath(new Object[] {root}));
    tree.setShowsRootHandles(true);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setCellRenderer(tcr = new FindResultsTreeCellRenderer());
    root.setAllowsChildren(true);

    if(Config.isDefaultMode()) {
      titledLabel.setIcon(GUIUtilities.loadIcon("find.png")); //$NON-NLS-1$
      
      miClear.setIcon(GUIUtilities.loadIcon("clear.png")); //$NON-NLS-1$
      miClearAndClose.setIcon(GUIUtilities.EMPTY_ICON);
      miClose.setIcon(GUIUtilities.EMPTY_ICON);
    }

    popupMenu.add(miClear);
    popupMenu.add(miClearAndClose);
    popupMenu.add(miClose);
    miClear.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(final ActionEvent e) {
        clearResults();
      }
    });
    miClearAndClose.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(final ActionEvent e) {
        clearResults();
        jNPad.setFindResultsVisible(false);
      }
    });
    miClose.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(final ActionEvent e) {
        jNPad.setFindResultsVisible(false);
      }
    });

    configure(CFG_COLOR);

    tree.addMouseListener(new MouseAdapter() {
      @Override 
      public void mousePressed(final MouseEvent e) {
        if (e.isPopupTrigger()) {
          showPopupMenu(e);
        }
      }

      @Override 
      public void mouseClicked(final MouseEvent e) {
        if (e.getModifiers() == InputEvent.BUTTON1_MASK && e.getClickCount() == 1) {
          handleValueChanged(new TreeSelectionEvent(tree,
                                                    tree.getSelectionPath(),
                                                    false,
                                                    tree.getSelectionPath(),
                                                    tree.getSelectionPath()));
        }
      }

      @Override 
      public void mouseReleased(final MouseEvent e) {
        if (e.getModifiers() == InputEvent.BUTTON1_MASK && e.getClickCount() > 1) {
          textReloadFocus();
        }
        else if (e.isPopupTrigger()) {
          showPopupMenu(e);
        }
      }
    });

    tree.addKeyListener(new KeyAdapter() {
      @Override
      public void keyPressed(final KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
          textReloadFocus();
        }
      }
    });

    tree.addTreeSelectionListener(new TreeSelectionListener() {
      @Override
      public void valueChanged(final TreeSelectionEvent e) {
        handleValueChanged(e);
      }
    });

    titledLabel.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(final ActionEvent e) {
        String actionCommand = e.getActionCommand();
        if (TitledLabel.ACTION_COMMAND_CLOSE.equals(actionCommand)) {
          jNPad.setFindResultsVisible(false);
        }
      }
    });
  }

  /**
   * Show popup menu.
   *
   * @param e MouseEvent
   */
  private void showPopupMenu(final MouseEvent e) {
    try {
      Point p = e.getPoint();
      TreePath treePath = tree.getPathForLocation( (int) p.getX(), (int) p.getY());
      if (treePath == null) { // mostrar popup del ?rbol (no del nodo)
        miClear.setEnabled(hasResults());
        SwingUtilities.updateComponentTreeUI(popupMenu);
        popupMenu.pack();
        popupMenu.show(e.getComponent(), e.getX(), e.getY());
      }
    }
    catch (Exception ex) {
      LOGGER.log(Level.WARNING, ex.getMessage(), ex);
    }
  }

  /**
   * Handle value changed.
   *
   * @param e TreeSelectionEvent
   */
  private void handleValueChanged(final TreeSelectionEvent e) {
    Object obj = tree.getLastSelectedPathComponent();
    if (obj instanceof DefaultMutableTreeNode) {
      obj = ((DefaultMutableTreeNode) obj).getUserObject();
      if (obj instanceof Text) {
        jNPad.selectSearchedText((Text) obj, tree);
      }
    }
  }

  /**
   * Text reload focus.
   */
  private void textReloadFocus() {
    Object obj = tree.getLastSelectedPathComponent();
    obj = ( (DefaultMutableTreeNode) obj).getUserObject();
    if (obj != null && (obj instanceof Text)) {
      jNPad.getActiveBuffer().requestFocus();
    }
  }

  /**
   * Checks for results.
   *
   * @return boolean
   */
  public boolean hasResults() {
    return root.getChildCount() > 0;
  }

  /**
   * Clear results.
   */
  public void clearResults() {
    root.removeAllChildren();
    treeModel.reload();
  }

  /**
   * Reload.
   */
  public void reload() {
    treeModel.reload();
  }

  /**
   * Configure.
   *
   * @param cfg the cfg
   * @see jnpad.config.Configurable#configure(int)
   */
  @Override
  public void configure(final int cfg) {
    if ( (cfg & CFG_COLOR) != 0) {
      titledLabel.setTitleFont(Config.TITLED_LABEL_FONT.getValue());
      titledLabel.setTitleColor(Config.TITLED_LABEL_FOREGROUND.getValue());
      titledLabel.setGradientColors(Config.TITLED_LABEL_GRADIENT1.getValue(), Config.TITLED_LABEL_GRADIENT2.getValue());
      titledLabel.setOrientation(Config.TITLED_LABEL_ORIENTATION.getValue());

      tree.setBackground(Config.TEXT_BACKGROUND.getValue());
      tree.setForeground(Config.TEXT_FOREGROUND.getValue());
      //tree.setFont(Config.TEXT_FONT.getValue());

      if (LAFUtils.isNimbusLAF()) {
        final Color selectionBackground = Config.TEXT_SELECTION_BACKGROUND.getValue();
        UIDefaults overrides = new UIDefaults();
        /*
        Object painter = new com.sun.java.swing.Painter<JComponent>() {
          public void paint(Graphics2D g, JComponent c, int w, int h) {
            g.setColor(selectionBackground);
            g.fillRect(0, 0, w, h);
          }
        };
        overrides.put("Tree:TreeCell[Focused+Selected].backgroundPainter", painter);
        overrides.put("Tree:TreeCell[Enabled+Selected].backgroundPainter", painter);
        //overrides.put("Tree:TreeCell[Enabled+Focused].backgroundPainter", painter);
        */
        overrides.put("Tree:TreeCell[Focused+Selected].backgroundPainter", selectionBackground); //$NON-NLS-1$
        overrides.put("Tree:TreeCell[Enabled+Selected].backgroundPainter", selectionBackground); //$NON-NLS-1$
        overrides.put("Tree:TreeCell[Enabled+Focused].backgroundPainter", selectionBackground); //$NON-NLS-1$
        tree.putClientProperty("Nimbus.Overrides", overrides); //$NON-NLS-1$
      }
    }

    tcr.configure(cfg);
  }

  /**
   * Adds the new found.
   *
   * @param text String
   * @param path String
   */
  public void addNewFound(String text, String path) {
    DefaultMutableTreeNode node = null;
    target = new DefaultMutableTreeNode(SearchBundle.getString("FindResultsPanel.result", text).concat(path), true); //$NON-NLS-1$
    Enumeration<?> enumeration = root.children();
    boolean flag;
    for (flag = false; !flag && enumeration.hasMoreElements();
         flag = node.toString().equals(target.toString()))
      node = (DefaultMutableTreeNode) enumeration.nextElement();

    if (flag)
      root.remove(node);
    root.add(target);
    target.setAllowsChildren(true);
    treeModel.reload();
  }

  /**
   * Adds the new text.
   *
   * @param text Text
   */
  public void addNewText(Text text) {
    DefaultMutableTreeNode node;
    target.add(node = new DefaultMutableTreeNode(text, false));
    node.setAllowsChildren(false);
    treeModel.reload();
  }

  /**
   * Show found target.
   */
  public void showFoundTarget() {
    TreeNode treeNode = null;
    if (target.getChildCount() > 0)
      treeNode = target.getChildAt(0);
    if (treeNode == null)
      tree.setSelectionPath(new TreePath(new Object[] {root, target}));
    else
      tree.setSelectionPath(new TreePath(new Object[] {root, target, treeNode}));
    //requestFocus();
  }

  /**
   * Request focus.
   *
   * @see javax.swing.JComponent#requestFocus()
   */
  @Override
  public void requestFocus() {
    if (tree != null) {
      tree.requestFocus();
    }
    else {
      super.requestFocus();
    }
  }

  /**
   * Request focus in window.
   *
   * @return true, if successful
   * @see javax.swing.JComponent#requestFocusInWindow()
   */
  @Override
  public boolean requestFocusInWindow() {
    if (tree != null) {
      return tree.requestFocusInWindow();
    }
    return super.requestFocusInWindow();
  }
  
}
