/*
 * 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.text;

import java.awt.Container;
import java.awt.event.ActionEvent;

import javax.swing.JComponent;
import javax.swing.text.JTextComponent;
import javax.swing.text.TextAction;

import jnpad.JNPadFrame;
import jnpad.GUIUtilities;

/**
 * The Class JNPadTextAction.
 *
 * @version 0.3
 * @since   jNPad v0.1
 */
public abstract class JNPadTextAction extends TextAction {
  /** UID */
  private static final long serialVersionUID = 6203869482295044332L;

  /**
   *
   * @param name String
   */
  public JNPadTextAction(String name) {
    super(name);
  }

  /**
   * 
   * @param e ActionEvent
   * @return EditTextArea
   */
  protected final JNPadTextArea getTextArea(ActionEvent e) {
    JTextComponent target = getTextComponent(e);
    if (target != null && target instanceof JNPadTextArea) {
      return (JNPadTextArea) target;
    }
    JNPadFrame jNPad = getJNPadParent(e);
    if (jNPad != null) {
      return jNPad.getActiveTextArea();
    }
    return null;
  }

  /**
   *
   * @param e ActionEvent
   * @return JNPadFrame
   */
  protected final JNPadFrame getJNPadParent(ActionEvent e) {
    JNPadFrame jNPad = null;

    // the source of the event is the first place to look
    Object source = e.getSource();
    if (source instanceof JComponent) {
      Container c = ( (JComponent) source).getTopLevelAncestor();
      if (c instanceof JNPadFrame) {
        jNPad = (JNPadFrame) c;
      }
    }

    // otherwise use 'getTextComponent'
    if (jNPad == null) {
      JTextComponent textComponent = getTextComponent(e);
      if (textComponent != null) {
        Container c = textComponent.getTopLevelAncestor();
        if (c instanceof JNPadFrame) {
          jNPad = (JNPadFrame) c;
        }
      }
    }

    if (jNPad == null) {
      jNPad = GUIUtilities.getJNPadFrame(e);
    }

    return jNPad;
  }

}
