/*
 * 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.awt.event.ItemEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import jnpad.JNPadFrame;
import jnpad.action.JNPadActions.Group;
import jnpad.config.Config;
import jnpad.config.Configurable;
import jnpad.ui.MnemonicHelper;
import jnpad.ui.status.StatusDisplayable;
import jnpad.ui.status.StatusDisplayable.StatusType;
import jnpad.util.Utilities;

/**
 * The Class SelectColorSchemeAction.
 *
 * @version 0.3
 * @since   jNPad v0.1
 */
public final class SelectColorSchemeAction extends JNPadAction {
  private File                            file;

  static final String                     NAME             = "select-colorscheme";                                     //$NON-NLS-1$

  private static Map<String, JNPadAction> map              = new HashMap<String, JNPadAction>();

  /** Logger */
  private static final Logger             LOGGER           = Logger.getLogger(SelectColorSchemeAction.class.getName());

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

  /**
   * Instantiates a new select color scheme action.
   *
   * @param jNPad the jNPad's frame
   * @param file the file
   * @param selected the selected
   * @param mnemonicHelper the mnemonic helper
   */
  public SelectColorSchemeAction(JNPadFrame jNPad, File file, boolean selected, MnemonicHelper mnemonicHelper) {
    super(jNPad, NAME, Group.CONFIGURE);
    this.file = file;
    
    final String label = Utilities.getFileBaseName(file.getPath());
    final String name  = NAME + Utilities.SPACE_STRING + label;

    setLabel(label);
    setName(name);

    if (mnemonicHelper != null) {
      char mnemonic = mnemonicHelper.getMnemonic(label);
      if (mnemonic != 0) {
        setMnemonic(mnemonic);
      }
    }

    setDescription(ActionBundle.getString(NAME.concat(".description"), label)); //$NON-NLS-1$

    setSelected(selected);
    setStateAction(true);
    
    map.put(name, this);
  }

  /**
   * Handle state changed.
   *
   * @param e ItemEvent
   * @see jnpad.action.JNPadAction#handleStateChanged(java.awt.event.ItemEvent)
   */
  @Override
  public void handleStateChanged(final ItemEvent e) {
    if (ItemEvent.SELECTED == e.getStateChange()) {
      final String colorscheme = getLabel();
      Properties prop = new Properties();
      BufferedReader in = null;
      try {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); //$NON-NLS-1$
        prop.load(in);
      }
      catch (IOException ex) {
        String msg = ActionBundle.getString(NAME.concat(".error"), colorscheme); //$NON-NLS-1$
        LOGGER.log(Level.WARNING, msg, ex);
        jNPad.setStatus(StatusType.ERROR, msg);
        return;
      }
      finally {
        try {
          if (in != null) {
            in.close();
          }
        }
        catch (IOException ex) {
          LOGGER.log(Level.WARNING, ex.getMessage(), ex);
        }
      }
      Config.putAll(prop);
      jNPad.configure(Configurable.CFG_COLOR | Configurable.CFG_FONT);
      jNPad.setStatus(ActionBundle.getString(NAME.concat(".message"), colorscheme, Config.JNPAD_COLORSCHEME.getValue()), StatusDisplayable.TIMEOUT_DEFAULT); //$NON-NLS-1$
      Config.JNPAD_COLORSCHEME.setValue(colorscheme);
    }
  }
  
  /**
   * Gets the completions for prefix.
   *
   * @param prefix the prefix
   * @return the completions for prefix
   */
  static List<String> getCompletionsForPrefix(String prefix) {
    List<String> list = new ArrayList<String>();
    for (String key : map.keySet()) {
      JNPadAction action = map.get(key);
      if (key.startsWith(prefix) && action.isEnabled()) {
        list.add(key);
      }
    }
    Collections.sort(list);
    return list;
  }
  
  /**
   * Perform action.
   *
   * @param name the name
   * @return true, if successful
   */
  static boolean performAction(String name) {
    JNPadAction action = map.get(name);
    if (action != null && action.isEnabled()) {
      action.setSelected(!action.isSelected());
      return true;
    }
    return false;
  }

}
