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.Level;

import de.ugoe.cs.util.console.Console;

/**
 * TODO comment
 * 
 * @version $Revision: $ $Date: 12.07.2012$
 * @author 2012, last modified by $Author: pharms$
 */
class VirtualKeySynonyms {
    
    /** */
    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)) {
            Console.traceln(Level.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 {
            Console.traceln(Level.WARNING, "no virtual key define for key id " + keyId);
            return null;
        }
    }

}
