// Module    : $RCSfile: VirtualKeySynonyms.java,v $
// Version   : $Revision: 0.0 $  $Author: pharms $  $Date: 12.07.2012 $
// Project   : KeyboardMaps
// Creation  : 2012 by pharms
// Copyright : Patrick Harms, 2012

package de.ugoe.cs.tasktree.keyboardmaps;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * TODO comment
 * 
 * @version $Revision: $ $Date: 12.07.2012$
 * @author 2012, last modified by $Author: pharms$
 */
class VirtualKeySynonyms {
    
    /** */
    private static Logger LOG = Logger.getLogger(KeyboardMap.class.getName());

    /** */
    private Map<Integer, List<VirtualKey>> synonyms = new HashMap<Integer, List<VirtualKey>>();

    /** */
    private Map<VirtualKey, Integer> keyIds = new HashMap<VirtualKey, Integer>();

    /**
     * TODO: comment
     * 
     * @param keyId
     * @param virtualKey
     */
    public void add(int keyId, VirtualKey virtualKey) {
        List<VirtualKey> synonymList = synonyms.get(keyId);

        if (synonymList == null) {
            synonymList = new ArrayList<VirtualKey>();
            synonyms.put(keyId, synonymList);
        }

        if (!synonymList.contains(virtualKey)) {
            // ensure that the latest determined virtual keys are considered first
            synonymList.add(0, virtualKey);
        }

        Integer existingKeyId = keyIds.get(virtualKey);

        if ((existingKeyId != null) && (existingKeyId != keyId)) {
            LOG.finest("virtual key " + virtualKey +
                       " is mapped to more than one key id (current is " + existingKeyId +
                       ", new is " + keyId + "). New key id will be used (" + keyId + ").");
        }

        keyIds.put(virtualKey, keyId);
    }

    /**
   *
   */
    public boolean containsKey(int keyId) {
        return synonyms.containsKey(keyId);
    }

    /**
     * TODO: comment
     * 
     * @param keyId
     * @return
     */
    public VirtualKey[] getVirtualKeySynonyms(int keyId) {
        List<VirtualKey> virtualKeys = synonyms.get(keyId);
        if (virtualKeys != null) {
            return virtualKeys.toArray(new VirtualKey[virtualKeys.size()]);
        }
        else {
            LOG.warning("no virtual key define for key id " + keyId);
            return null;
        }
    }

}
