package me.hammerle.supersnuvi.input;

import java.util.EnumMap;
import java.util.LinkedList;
import javafx.scene.input.KeyCode;

public class KeyHandler implements IKeyHandler
{
    private final LinkedList<KeyCode> removeQueue;
    private final EnumMap<KeyCode, Integer> keys;
    private final EnumMap<KeyCode, Integer> justReleased;
    
    public KeyHandler()
    {
        keys = new EnumMap(KeyCode.class);
        justReleased = new EnumMap(KeyCode.class);
        removeQueue = new LinkedList<>();
    }
    
    public void pressKey(KeyCode key)
    {
        keys.putIfAbsent(key, 0);
    }
    
    public void releaseKey(KeyCode key)
    {
        removeQueue.add(key);
    }
    
    @Override
    public int getKeyDownTime(KeyCode key)
    {
        Integer i = keys.get(key);
        return i != null ? i : 0;
    }
    
    @Override
    public void resetKeyTime(KeyCode key)
    {
        keys.replace(key, 0);
    }
    
    @Override
    public int isKeyJustReleased(KeyCode key)
    {
        Integer i = justReleased.get(key);
        return i != null ? i : -1;
    }
    
    @Override
    public boolean isKeyDown(KeyCode key)
    {
        return keys.containsKey(key);
    }

    public void tick() 
    {
        keys.replaceAll((k, v) -> v + 1);
        justReleased.clear();
        
        removeQueue.forEach(key -> 
        {
            Integer i = keys.remove(key);
            if(i != null)
            {
                justReleased.put(key, i);
            }
        });
        removeQueue.clear();
    }
}
