/*
 * 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_REMOVE_END_LINES;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;

import jnpad.JNPadFrame;
import jnpad.action.JNPadActions.Group;
import jnpad.config.Accelerators;
import jnpad.text.Buffer;
import jnpad.text.IEditAction;
import jnpad.text.TextUtilities;
import jnpad.ui.status.StatusDisplayable.StatusType;

/**
 * The Class RemoveEndSpacesAction.
 *
 * @version 0.3
 * @since jNPad 0.1
 */
public final class RemoveEndSpacesAction extends JNPadAction implements IEditAction {
  /** Logger */
  private static final Logger LOGGER           = Logger.getLogger(RemoveEndSpacesAction.class.getName());

  /** UID */
  private static final long   serialVersionUID = 3469606959782769250L;

  /**
   * Instantiates a new removes the end spaces action.
   *
   * @param jNPad the jNPad's frame
   */
  public RemoveEndSpacesAction(JNPadFrame jNPad) {
    super(jNPad,
          ACTION_NAME_REMOVE_END_LINES,
          Group.EDIT,
          Accelerators.REMOVE_END_SPACES, null);
  }

  /**
   * Perform action.
   *
   * @see jnpad.action.JNPadAction#performAction()
   */
  @Override
  public void performAction() {
    Buffer buffer = jNPad.getActiveBuffer();

    if (buffer != null) {
      try {
        buffer.beginCompoundEdit();

        JTextComponent target = buffer.getSelectedTextArea();
        Document doc = target.getDocument();

        Element map = doc.getDefaultRootElement();
        int count = map.getElementCount();
        for (int i = 0; i < count; i++) {
          Element lineElement = map.getElement(i);
          int start = lineElement.getStartOffset();
          int end = lineElement.getEndOffset() - 1;
          end -= start;
          String text = doRemove(TextUtilities.getText(doc, start, end));
          doc.remove(start, end);
          if (text != null) {
            doc.insertString(start, text, null);
          }
        }
      }
      catch (Exception ex) {
        LOGGER.log(Level.WARNING, ex.getMessage(), ex);
        jNPad.setStatus(StatusType.ERROR, "Error - ".concat(getLabel())); //$NON-NLS-1$
      }
      finally {
        buffer.endCompoundEdit();
      }
    }
  }

  /**
   * Do remove.
   *
   * @param in String
   * @return String
   */
  private String doRemove(String in) {
    int end = in.length();
    while (--end >= 0 && Character.isWhitespace(in.charAt(end)))
      ;
    return (end < 0) ? null : in.substring(0, end + 1);
  }

}
