#include "MenuTextJoystick.h"

void MenuTextJoystick::Init(std::weak_ptr<Entity> self)
{
	auto wicon = std::make_shared<Entity>();
	icon = wicon;
	wicon->ani.png = L"menu_key";
	wicon->ani.hideLayerList.insert(1);
	wicon->x = x - 32;
	wicon->y = y;
	gameFunc->SetEntity(shared_from_this(), wicon);
	Entity::Init(self);
}

void MenuTextJoystick::Step()
{
	switch (stateID)
	{
	default:
	case 0:
		if (gameFunc)
		{
			if (gameFunc->GetGameControllerKeyName)
			{
				if (GetInputSetting())
				{
					gameFunc->GetGameControllerKeyName(&name, GetBind(GetInputSetting()));
					//设置图标
					auto wicon = icon.lock();
					if (wicon)
					{
						wicon->ani.sprite_index.clear();
						wicon->ani.sprite_index.append(L"joystick_");
						wicon->ani.sprite_index.append(name.data());
					}
					//设置文本
					if (el.eid != name.data())
						el.eid = name.data();
				}
			}
		}
		break;
	case 1://手柄是否所有键已放开
		if (gameFunc)
		{
			if (gameFunc->GetAnyGameControllerKeyPress)
			{
				SDL_GameControllerButtonBind keyBind;
				auto p = GetInputSetting();
				auto joy = p->pGameController;
				if (!gameFunc->GetAnyGameControllerKeyPress(joy, &keyBind))
					stateID = 2;
			}
		}
		break;
	case 2://捕获键状态
		if (gameFunc)
		{
			if (gameFunc->GetAnyGameControllerKeyPress && GetInputSetting())
			{
				SDL_GameControllerButtonBind keyBind;
				auto p = GetInputSetting();
				auto joy = p->pGameController;
				if (gameFunc->GetAnyGameControllerKeyPress(joy, &keyBind))
				{
					*GetBind(p) = keyBind;
					stateID = 0;
					//设置图标
					auto wicon = icon.lock();
					if (wicon)
						wicon->ani.sprite_index = L"";
					//设置文本
					ani.png = ani.sprite_index = L"";
					el.flag.text = true;
					gameFunc->GetGameControllerKeyName(&name, GetBind(p));
					el.eid = name.data();
					gameFunc->SaveConfig();
					//放开其他键
					auto we = GetPlayer(gameFunc->entityRes).lock();
					if (we)
					{
						we->input.key = 0;
						we->inputLock.key = 0xffffffff;
					}
				}
			}
		}
		break;
	}
}

void MenuTextJoystick::SetState(int stateID, int lr)
{
	this->stateID = stateID;
	if (stateID == 1)
	{
		ani.png = L"menu_CS_title";
		ani.sprite_index = L"msg_pressAnyKey";
		el.eid = L"";
		el.flag.text = false;
	}
}
