#include "UiFrameWork.h"

std::map<uint64_t , int>UI_HOVER_ZORDER;
std::map<uint64_t, UiFrameWork*>UI_HOVER_OBJECT;

void UiFrameWork::OnHoverEvent(Event* evt) {
	//每当UI类被悬停时就会像Map 书写自身位置
	UI_HOVER_ZORDER[this->GetObjectID()] = this->GetZOrder();
	UI_HOVER_OBJECT[this->GetObjectID()] = this;

	//取的Map的最大层的对象名称
	auto MaxZorderMap = std::max_element(UI_HOVER_ZORDER.begin(), UI_HOVER_ZORDER.end(), [](std::pair<std::uint64_t, int> left, std::pair<std::uint64_t, int> right) { return left.second < right.second; });

	std::map<uint64_t, UiFrameWork*>::reverse_iterator   iter;
	for (iter = UI_HOVER_OBJECT.rbegin(); iter != UI_HOVER_OBJECT.rend(); iter++) {
		//如果是最大层那么调用悬停如果不是就调用移出悬停
		if (iter->first == MaxZorderMap->first) {
			iter->second->OnHover();
		}
		else {
			iter->second->OnOut();
		}
	}
	
}

void UiFrameWork::OnOutEvent(Event* evt) {
	//每当UI类不在被悬停时 就会从Map中 移除自身位置
	UI_HOVER_ZORDER.erase(this->GetObjectID());
	UI_HOVER_OBJECT.erase(this->GetObjectID());

	this->OnOut();

	//取的Map的最大层的对象名称
	auto MaxZorderMap = std::max_element(UI_HOVER_ZORDER.begin(), UI_HOVER_ZORDER.end(), [](std::pair<std::uint64_t, int> left, std::pair<std::uint64_t, int> right) { return left.second < right.second; });

	std::map<uint64_t, UiFrameWork*>::reverse_iterator   iter;
	for (iter = UI_HOVER_OBJECT.rbegin(); iter != UI_HOVER_OBJECT.rend(); iter++) {
		//如果是最大层那么调用悬停如果不是就调用移出悬停
		if (iter->first == MaxZorderMap->first) {
			iter->second->OnHover();
		}
		else {
			iter->second->OnOut();
		}
	}
}

void UiFrameWork::RemoveZorder()
{
	UI_HOVER_ZORDER.erase(this->GetObjectID());
	UI_HOVER_OBJECT.erase(this->GetObjectID());
}


void UiFrameWork::OnHover()
{

}

void UiFrameWork::OnOut()
{
}

void UiFrameWork::Init()
{
	//UI类 都会增加鼠标监听
	ComponentPtr comp = new MouseSensor;
	AddComponent(0, comp);
	//增加悬停和移出的响应事件
	AddListener<MouseHoverEvent>(Closure(this, &UiFrameWork::OnHoverEvent));
	AddListener<MouseOutEvent>(Closure(this, &UiFrameWork::OnOutEvent));
}
