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

import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;

/**
 * 
 * @version 0.3
 * @since   jNPad v0.1
 */
public class MnemonicHelper {
  private List<Character> l_mnemonics = new ArrayList<Character>();

  /**
   * 
   * @param text String
   * @return char
   */
  public char getMnemonic(String text) {
    if (text == null || text.length() == 0) {
      return 0;
    }

    int mnemonicPos = 0;
    char mnemonic;
    text = text.toLowerCase();
    int textLength = text.length();
    do {
      mnemonic = text.charAt(mnemonicPos++);
      if (checkIsOk(mnemonic)) { // !isMnemonicUsed(mnemonic) && !Character.isWhitespace(mnemonic)
        l_mnemonics.add(mnemonic);
        return mnemonic;
      }
    } while (mnemonicPos < textLength);

    return 0;
  }

  /**
   * 
   * @param mnemonic char
   * @return boolean
   */
  private boolean checkIsOk(char mnemonic) {
    return !isMnemonicUsed(mnemonic) && !Character.isWhitespace(mnemonic) &&
              (((mnemonic >= 'A') && (mnemonic <= 'Z')) ||
                      ((mnemonic >= 'a') && (mnemonic <= 'z')) ||
                      ((mnemonic >= '0') && (mnemonic <= '9')));
  }

  /**
   * 
   * @param button JButton
   * @return char
   */
  public char getMnemonic(JButton button) {
    return getMnemonic(button.getText());
  }

  /**
   * 
   * @param ch char
   * @return boolean
   */
  public boolean isMnemonicUsed(char ch) {
    return l_mnemonics.indexOf(ch) != -1;
  }

  /**
   *
   */
  public void clear() {
    l_mnemonics.clear();
  }
}
