package sillysagiri;

import java.util.Hashtable;

public final class Input {
  public Hashtable<Integer, Integer> hash_keyState = new Hashtable<>();
  
  public int state_anyKey = 0;
  public int state_touchState = Sagiri.TOUCH_NONE;
  public int state_lastKey = 0;

  public int touchX = 0;
  public int touchY = 0;

  public Input()
  {
  }
  
  public final void Update()
  {
    for (Integer key : hash_keyState.keySet())
    {
      int value = hash_keyState.get(key);
      if (value == -1) hash_keyState.remove(key);
      else hash_keyState.put(key, value+1);
    }

    if (state_anyKey != 0) state_anyKey++;
    state_touchState = Sagiri.TOUCH_NONE;
  }
  
  public final void HandleKeyDown(int keycode)
  {
    Integer value = hash_keyState.get(keycode);

    if (value != null)
      hash_keyState.put(keycode, new Integer(Math.max(value, 1)));
    else
      hash_keyState.put(keycode, 1);

    state_anyKey = Math.max(state_anyKey, 1);
    state_lastKey = keycode;
  }
  
  public final void HandleKeyUp(int keycode)
  {
    hash_keyState.put(keycode, -1);
    state_anyKey = -1;
    state_lastKey = keycode;
  }
  
  public final void HandleTouch(int phase, int x, int y)
  {
    state_touchState = phase;
    touchX = x;
    touchY = y;
  }

  public final boolean IsKeyHeld(int keycode)
  {
    Integer value = hash_keyState.get(keycode);

    if (value != null)
      return value.intValue() > 0;
    else
      return false;
  }

  public final boolean IsKeyHeld(int[] keycode)
  {
    for (int i : keycode)
      if (IsKeyHeld(keycode[i])) return true;
    return false;
  }

  public final boolean IsKeyDown(int keycode)
  {
    Integer value = hash_keyState.get(keycode);

    if (value != null)
      return value.intValue() == 0;
    else
      return false;
  }

  public final boolean IsKeyDown(int[] keycode)
  {
    for (int i : keycode)
      if (IsKeyDown(keycode[i])) return true;
    return false;
  }

  public final boolean IsKeyReleased(int keycode)
  {
    Integer value = hash_keyState.get(keycode);

    if (value != null)
      return value.intValue() == -1;
    else
      return false;
  }

  public final boolean IsKeyReleased(int[] keycode)
  {
    for (int i : keycode)
      if (IsKeyReleased(keycode[i])) return true;
    return false;
  }

  public final boolean IsKeyHeldAny() { return state_anyKey > 1; }
  public final boolean IsKeyDownAny() { return state_anyKey == 1; }
  public final boolean IsKeyReleasedAny() { return state_anyKey == -1; }

  public final int getKeyStatus(int keycode) { return hash_keyState.get(keycode); }
}
