using UnityEngine;
using System.Collections;

public class Gamepad : MonoBehaviour {

	public enum e_controller_type {MINION, MONSTER, MENU};
	
	[SerializeField] public MinionManager			minionsManager;
	[SerializeField] public Movements					monsterMovements;
	public e_controller_type								controllerType;
	
	int JoyCount = -1;
	float DeadZone = 0.35F;
	float NegDeadZone = 0.00F;

	void Start (){
		NegDeadZone = DeadZone * (-1.0F);
		JoyCount = Input.GetJoystickNames().Length;
	}
	
	void Update (){
		float XAxis;
		float YAxis;
		if (controllerType == e_controller_type.MONSTER){
			XAxis = (Input.GetAxis("Joy0X"));
			YAxis = (Input.GetAxis("Joy0Y"));
			doAnlgLeft(XAxis, YAxis);
			if (Input.GetButtonDown("A-J1"))
				monsterMovements.Action();
		}
		else if (controllerType == e_controller_type.MINION){
			if (Input.GetButtonDown("J2-RB"))
				minionsManager.FocusNextMinion();
			if (Input.GetButtonDown("J2-LB"))
				minionsManager.FocusPrevMinion();
			XAxis = (Input.GetAxis("Joy1X"));
			YAxis = (Input.GetAxis("Joy1Y"));
			doAnlgLeft(XAxis, YAxis);
		}
	}
	
	public bool hardwareRequirementsMet()
	{
		JoyCount = Input.GetJoystickNames().Length;
		if (JoyCount >= 2)
			return true;
		return false;
	}

	void doAnlgLeft(float XAxis, float YAxis)
	{
		if (XAxis > DeadZone && YAxis < DeadZone && YAxis > NegDeadZone)
        {
			if (controllerType == e_controller_type.MONSTER){
				monsterMovements.NewInputAction(Movements.e_movement.RIGHT);
			}
			else
				minionsManager.NewInputAction(Movements.e_movement.RIGHT);
        	return;
        }
        if (XAxis <= DeadZone && XAxis >= NegDeadZone && YAxis > DeadZone)
        {
			if (controllerType == e_controller_type.MONSTER)
				monsterMovements.NewInputAction(Movements.e_movement.UP);
			else
				minionsManager.NewInputAction(Movements.e_movement.UP);
        	return;
        }
        if (XAxis <= NegDeadZone && YAxis >= NegDeadZone && YAxis < DeadZone)
        {
			if (controllerType == e_controller_type.MONSTER)
				monsterMovements.NewInputAction(Movements.e_movement.LEFT);
			else
				minionsManager.NewInputAction(Movements.e_movement.LEFT);
        	return;
        }
        if (XAxis >= NegDeadZone && XAxis <= DeadZone && YAxis < NegDeadZone)
        {
			if (controllerType == e_controller_type.MONSTER)
				monsterMovements.NewInputAction(Movements.e_movement.DOWN);
			else
				minionsManager.NewInputAction(Movements.e_movement.DOWN);
        	return;
        }
    }
}
