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

import static jnpad.action.JNPadActions.ACTION_NAME_SET_READ_ONLY;

import java.awt.event.ItemEvent;

import jnpad.GUIUtilities;
import jnpad.JNPadFrame;
import jnpad.action.JNPadActions.Group;
import jnpad.config.Accelerators;
import jnpad.text.Buffer;

/**
 * The Class SetReadOnlyAction.
 *
 * @version 0.3
 * @since   jNPad v0.1
 */
public final class SetReadOnlyAction extends JNPadAction {
  /** UID */
  private static final long serialVersionUID = 1581591013039732646L;

  /**
   * Instantiates a new sets the read only action.
   *
   * @param jNPad the jNPad's frame
   */
  public SetReadOnlyAction(JNPadFrame jNPad) {
    super(jNPad,
          ACTION_NAME_SET_READ_ONLY,
          Group.FORMAT,
          Accelerators.SET_READ_ONLY, "set-read-only-off.png"); //$NON-NLS-1$
    
    setSelected(false);
    setStateAction(true);
  }

  /**
   * Sets the selected.
   *
   * @param b the new selected
   * @see jnpad.action.JNPadAction#setSelected(boolean)
   */
  @Override
  public void setSelected(boolean b) {
    if (isSelected() != b) {
      setIcon(b ? GUIUtilities.loadIcon("set-read-only-on.png") : GUIUtilities.loadIcon("set-read-only-off.png")); //$NON-NLS-1$ //$NON-NLS-2$
    }
    super.setSelected(b);
  }

  /**
   * Handle state changed.
   *
   * @param e the e
   * @see jnpad.action.JNPadAction#handleStateChanged(java.awt.event.ItemEvent)
   */
  @Override
  public void handleStateChanged(final ItemEvent e) {
    Buffer buffer = jNPad.getActiveBuffer();
    if (buffer != null) {
      boolean on = ItemEvent.SELECTED == e.getStateChange();
      buffer.setReadOnly(on);
      setIcon(on ? GUIUtilities.loadIcon("set-read-only-on.png") : GUIUtilities.loadIcon("set-read-only-off.png"));  //$NON-NLS-1$//$NON-NLS-2$
    }
  }

}
