/*
 * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 */
package com.sun.glass.ui;

import com.sun.glass.events.GestureEvent;
import com.sun.glass.events.TouchEvent;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Alexey Semenyuk
 */
public class TouchInputSupport
{
    private int touchCount = 0;

    private boolean filterTouchCoordinates;
    private Map<Long, Integer> touchX;
    private Map<Long, Integer> touchY;

    public TouchInputSupport(boolean filterTouchCoordinates) {
        this.filterTouchCoordinates = filterTouchCoordinates;
        if (filterTouchCoordinates) {
            touchX = new HashMap<Long, Integer>();
            touchY = new HashMap<Long, Integer>();
        }
    }

    public int getTouchCount() {
        return touchCount;
    }

    public void notifyBeginTouchEvent(View view, int modifiers, boolean isDirect,
                                      int touchEventCount) {
        view.notifyBeginTouchEvent(modifiers, isDirect, touchEventCount);
    }

    public void notifyEndTouchEvent(View view) {
        view.notifyEndTouchEvent();
    }

    public void notifyNextTouchEvent(View view, int state, long id, int x, int y,
                                     int xAbs, int yAbs) {
        switch (state) {
            case TouchEvent.TOUCH_RELEASED:
                touchCount--;
                break;
            case TouchEvent.TOUCH_PRESSED:
                touchCount++;
                break;
        }

        if (filterTouchCoordinates) {
            state = filterTouchInputState(state, id, x, y);
        }

        view.notifyNextTouchEvent(state, id, x, y, xAbs, yAbs);
    }

    private int filterTouchInputState(int state, long id, int x, int y) {
        switch (state) {
            case TouchEvent.TOUCH_RELEASED:
                touchX.remove(id);
                touchY.remove(id);
                break;
            case TouchEvent.TOUCH_MOVED:
                if (x == touchX.get(id) && y == touchY.get(id)) {
                    state = TouchEvent.TOUCH_STILL;
                    break;
                }
                // fall through;
            case TouchEvent.TOUCH_PRESSED:
                touchX.put(id, x);
                touchY.put(id, y);
                break;
        }
        return state;
    }
}
