#include "controller.h"

using namespace godot;

void Controller::_bind_methods()
{
	ClassDB::bind_method(D_METHOD("get_flags"), &Controller::get_flags);
	ClassDB::bind_method(D_METHOD("set_flags","p_flags"), &Controller::set_flags);
	ADD_PROPERTY(PropertyInfo(Variant::INT, "flags"), "set_flags", "get_flags");
	ClassDB::bind_method(D_METHOD("get_target"), &Controller::get_target);
	ClassDB::bind_method(D_METHOD("set_target","p_target"), &Controller::set_target);
	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "target", PROPERTY_HINT_RESOURCE_TYPE, "Vector2"), "set_target", "get_target");
}

Controller::Controller()
{
	flags=0;
	target=Vector2(0,0);
}
Controller::~Controller(){}

void Controller::_process(double delta)
{
	if (get_multiplayer()->get_unique_id()!=get_multiplayer_authority()) return;
	// Kinda janky but this might come in handy later
	target=parent->get_global_mouse_position();
}

void Controller::_enter_tree()
{
	set_root_path(NodePath("."));
	Ref<SceneReplicationConfig> conf=memnew(SceneReplicationConfig);
	set_replication_config(conf);
	conf->add_property(":flags");
	conf->add_property(":target");
}

void Controller::_unhandled_key_input(const Ref<InputEvent> &p_event)
{
	if (get_multiplayer()->get_unique_id()!=get_multiplayer_authority()) return;
	UtilityFunctions::print("pre ",flags);
	//これ嫌い
	if (p_event->is_action_pressed("move_up",false,true)) flags|=1;
	if (p_event->is_action_released("move_up",true)) flags&=-2;
	if (p_event->is_action_pressed("move_down",false,true)) flags|=2;
	if (p_event->is_action_released("move_down",true)) flags&=-3;
	if (p_event->is_action_pressed("move_left",false,true)) flags|=4;
	if (p_event->is_action_released("move_left",true)) flags&=-5;
	if (p_event->is_action_pressed("move_right",false,true)) flags|=8;
	if (p_event->is_action_released("move_right",true)) flags&=-9;
	//Viewport.set_input_as_handled(); // I have no idea how this figures out which input to flag as handled.
}

void Controller::set_flags(const int p_flags) { flags=p_flags; }
int Controller::get_flags() const { return flags; }

void Controller::set_target(const Vector2 p_target) { target=p_target; }
Vector2 Controller::get_target() const { return target; }