package me.hammerle.supersnuvi.javafx;

import javafx.scene.input.KeyCode;

public class KeyBinding implements IKeyBinding
{
    private boolean isDown;
    private boolean justReleased;
    private int downTime;
    
    private KeyCode code;
    private boolean isEdited;
    
    private final String name;
    
    public KeyBinding(String name, KeyCode code)
    {
        downTime = 0;
        justReleased = false;
        this.code = code;
        this.name = name;
    }
    
    @Override
    public String getName() 
    {
        return name;
    }
    
    @Override
    public String getKeyName() 
    {
        return code.getName();
    }
    
    public void setEditStatus(boolean b)
    {
        isEdited = b;
    }
    
    public KeyCode getKeyCode()
    {
        return code;
    }
    
    public void setKeyCode(KeyCode code)
    {
        this.code = code; 
    }
    
    public void press()
    {
        isDown = true;
    }
    
    public void release()
    {
        isDown = false;
    }
    
    public void tick()
    {   
        if(isDown)
        {
            downTime++;
        }
        else if(justReleased)
        {
            downTime = 0;
            justReleased = false;
        }
        else if(downTime > 0)
        {
            justReleased = true;
        }
    }
    
    @Override
    public boolean isDown()
    {
        return downTime > 0;
    }

    @Override
    public int getDownTime() 
    {
        return downTime;
    }

    @Override
    public boolean wasJustReleased() 
    {
        return justReleased;
    }
    
    @Override
    public void resetTime() 
    {
        downTime = 0;
    }

    @Override
    public String toString() 
    {
        if(isEdited)
        {
            return "[...]    ";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(code.getName());
        if(sb.length() < 9)
        {
            sb.append("         ".substring(sb.length()));
        }
        return sb.toString();
    }
}
