//
//  lcd_gui_touch.c	  Part of GUI support library, Touch panel action handler
//  Copyright(C)2014 Toyohiko Togashi tog001@nifty.com
//
//
//  This program is free software; you can redistribute it and/or modify it under the terms of the
//  GNU General Public License as published by the Free Software Foundation; either version 3
//  of the License, or (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
//  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//  See the GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License along with this program.
//  If not, see <http://www.gnu.org/licenses/>
//
//
//    Update history
//    ---------- ----- -------------------------------------------
//    2014.02.15 v0.0  First cording
//    2014.03.15 v0.2  Commit
//

#include <stddef.h>
#include "lcd_gui_figure.h"
#include "lcd_gui_manage.h"				// lcd_guiFindGroupByPoint()...
#include "lcd_gui_touch.h"				// LCD_GUI_TOUCH_...
#include "lcd_touch.h"					// HW Driver lcd_touchPoint()

//
//	Touch sense
//
void lcd_guiHandlerTouch(struct lcd_gui *root){
	static struct lcd_guiGroup		*group = NULL;
	static int						count;
	struct lcd_guiCoordinate		point;
	short							z;

	z = lcd_touchPoint(&point.x, &point.y);
	if (z > LCD_GUI_TOUCH_THRESHOLD) {
#ifdef DEBUG1
		lcd_drawRect(point.x, point.y, 5, 5, LCD_COLOR_PINK);		// DEBUG
#endif	//DEBUG
		count++;
		if (count > LCD_GUI_TOUCH_CHATTER_CANCEL) {
			// Touch "ON"
			if (group == NULL) {
				// Touch in event (one time)
				group = lcd_guiFindGroupByPoint(root, &point);	// Search target figure with user program
				if (group == NULL) {
					group = (struct lcd_guiGroup *)root;
				}
#ifdef LCD_GUI_TOUCH_TAKE_OVER_CALLBACK
				while(group != NULL) {
					if (group->eventProg) {
						break;
					}
					group = lcd_guiGetGroupParent(group);
				}
#endif
				if ((group != NULL) && (group->eventProg != NULL)) {
					struct lcd_guiGroup	*r;

					for(r = group; r != NULL; r = lcd_guiGetParent(r)) {
						point.x -= r->area.x;
						point.y -= r->area.y;
					}
					group->eventProg(LCD_GUI_EVENT_TOUCH, &point, group);
				}
			} else {
				// Touch on keep
				if (group->eventProg != NULL) {
					struct lcd_guiGroup	*r;

					for(r = group; r != NULL; r = lcd_guiGetParent(r)) {
						point.x -= r->area.x;
						point.y -= r->area.y;
					}
					group->eventProg(LCD_GUI_EVENT_SLIDE, &point, group);
				}
			}
		}
	} else {
		// Touch "OFF"
		if (group) {
			// Touch out event (one time)
			if (group->eventProg) {
				group->eventProg(LCD_GUI_EVENT_RELEASE, NULL, group);
			}
			group = NULL;
		} else {
			// Touch off keep
		}
		count = 0;
	}

	return;
}

