#include "TZ_Vendor_debug_tl.h"
#include "tl_tui_bc_error_msg.h"
#include "Vendor_Interface.h"
#include "TZ_Vendor_tl.h"
#include "TuiControl.h"
#include "TuiTouch.h"
#include "TuiState.h"
#include "TuiScreenProperty.h"
#include "TuiLayout.h"

TouchBuffer touchBuffer[MAX_MULTI_TOUCH] = { {0,0,NONE_TOUCH_EVENT}, {0,0,NONE_TOUCH_EVENT} }; // support 2 fingers touch at sametime.

EEndOfTouch endOfTouch = (EEndOfTouch)0;

TuiState doTouchEvent(uint32_t x, uint32_t y, uint32_t type) {
	TouchEvent te;

	DBG_LOG("%s doTouchEvent x:%d, y:%d, type:%d, state:0x%x", LOG_TAG, x, y, type, getState());
	if (getState() == SESSION_ON_TUI_STATE) {

		te.x = x;
		te.y = y;
		te.type = type;

		executeTouchEvent(te);
	}

	return getState();
}

void executeTouchEvent(TouchEvent touch) {

	ResponseControl rc = executeControl(touch);
	if (rc.changeState != NONE_TUI_STATE) {
		DBG_LOG("bctui executeTouchEvent retControl.changeState:0x%x", rc.changeState);
		changeState(rc.changeState);
	}
}

void clearTouchEvent() {
	uint32_t ret;
	uint32_t x_out, y_out, type_out;
	do {
		ret = getTuiEvent(&x_out, &y_out, &type_out); // need refactoring
	} while (ret == TZ_API_OK || ret == BC_TUI_IGNORE_TOUCH);
}


EEndOfTouch isEndOfTouch() {
	return endOfTouch;
}

void setEndOfTouch(EEndOfTouch isEnd) {
	endOfTouch = isEnd;
}

void rotateCoodinate(uint32_t* x, uint32_t* y, RotationType rotation) {
	uint32_t buffer;

	switch (rotation) {
	case NONE_ROTATION_TYPE:
		if (getScreenType() == SCREEN_TYPE_Q2_MAIN) {
		    DBG_LOG("rotate touch x_in=%d, y_in=%d", *x, *y);
            *y = getScreenHeight() - *y;
            *x = getScreenWidth() - *x;
            DBG_LOG("rotate touch x=%d, y=%d", *x, *y);
    	}
		break;
	case CLOCKWISE_ROTATION_TYPE:
		DBG_LOG("rotate touch x_in=%d, y_in=%d", *x, *y);
		buffer = *y;
		*y = getScreenWidth() - *x;
		*x = buffer;
		DBG_LOG("rotate touch x=%d, y=%d", *x, *y);
		break;
	case COUNTER_CLOCKWISE_ROTATION_TYPE:
        DBG_LOG("rotate touch x_in=%d, y_in=%d", *x, *y);
        buffer = *x;
        *x = getScreenHeight() - *y;
        *y = buffer;
        DBG_LOG("rotate touch x=%d, y=%d", *x, *y);
		break;
	default:
		break;
	}

}
