/*
 * 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 java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;

import jnpad.JNPadFrame;
import jnpad.action.JNPadActions.Group;
import jnpad.text.JNPadTextArea;
import jnpad.text.Buffer;
import jnpad.text.IEditAction;
import jnpad.text.ISelectionAction;
import jnpad.ui.status.StatusDisplayable.StatusType;
import jnpad.util.Utilities;

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

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

  /**
   * Instantiates a new <code>AlignStringsAction</code>.
   *
   * @param jNPad the jNPad's frame
   * @param name the name
   * @param defaultAccelerator the default accelerator
   */
  protected AlignStringsAction(JNPadFrame jNPad, String name, KeyStroke defaultAccelerator) {
    super(jNPad, name, Group.FORMAT, defaultAccelerator, null);
  }

  /**
   * Align strings.
   *
   * @param delimiter String
   */
  protected void alignStrings(String delimiter) {
    Buffer buffer = jNPad.getActiveBuffer();
    if (buffer != null) {
      try {
        buffer.beginCompoundEdit();

        JNPadTextArea textArea = buffer.getSelectedTextArea();
        if (!textArea.isEditable() || !textArea.hasSelection())
          return;

        int startLine = textArea.getLineOfOffset(textArea.getSelectionStart());
        int endLine = textArea.getLineOfOffset(textArea.getSelectionEnd());

        if (endLine - startLine < 1)
          return;

        int max = -1;
        for (int i = startLine; i <= endLine; i++) {
          String text = textArea.getLineText(i);
          int count = Utilities.countMatches(text, delimiter);
          if (count > max)
            max = count;
        }

        if (max < 0)
          return;

        int pos = 0;
        for (int i = 0; i < max; i++) {
          pos = alignStrings(textArea, delimiter, pos + 1);
        }
      }
      catch (Exception ex) {
        LOGGER.log(Level.WARNING, ex.getMessage(), ex);
        jNPad.setStatus(StatusType.ERROR, "Error - ".concat(getLabel())); //$NON-NLS-1$
      }
      finally {
        buffer.endCompoundEdit();
      }
    }
  }

  /**
   * Align strings.
   *
   * @param textArea the text area
   * @param delimiter the delimiter
   * @param pos the pos
   * @return the int
   * @throws BadLocationException the bad location exception
   */
  private int alignStrings(JNPadTextArea textArea, String delimiter, int pos) throws BadLocationException {
    int startLine = textArea.getLineOfOffset(textArea.getSelectionStart());
    int endLine = textArea.getLineOfOffset(textArea.getSelectionEnd());

    if (endLine - startLine < 1)
      return -1;

    int maxCol = -1;
    for (int i = startLine; i <= endLine; i++) {
      String text = textArea.getLineText(i);
      int col = Utilities.indexOf(text, delimiter, pos);
      if (col > maxCol)
        maxCol = col;
    }

    if (maxCol < 0)
      return -1;

    for (int i = startLine; i <= endLine; i++) {
      String text = textArea.getLineText(i);
      int col = Utilities.indexOf(text, delimiter, pos);
      if (col == Utilities.INDEX_NOT_FOUND)
        continue;
      if (col < maxCol) {
        String spaces = Utilities.spaces(maxCol - col);
        textArea.insert(spaces, col + textArea.getLineStartOffset(i));
      }
    }

    return maxCol;
  }

}
