using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerInput : MonoBehaviour {

	Joycon joyconL,joyconR;
	public Vector2 walkDirection;
	public Vector2 cameraMovement;

	JoyconManager joyconMgr;
	// Use this for initialization
	void Start () {
		// joyconL = GameObject.Find("JoyCon(L)").GetComponent<JoyconController>();
		// joyconR = GameObject.Find("JoyCon(R)").GetComponent<JoyconController>();
		// if(!(joyconL || joyconR))
		// 	Debug.Log("Cannot find joycon Controller");
		joyconMgr = JoyconManager.Instance;
		//init two joycon;
		joyconL = joyconMgr.GetJoycon(JoyconManager.JoyconType.left);
		joyconR = joyconMgr.GetJoycon(JoyconManager.JoyconType.right);

		walkDirection = new Vector2(0,0);
		cameraMovement = new Vector2(0,0);
	}
	
	// Update is called once per frame
	void Update () {
		if(isConnected()){
			ushort stickX = joyconL.GetStickPrecal()[0];
			ushort stickY = joyconL.GetStickPrecal()[1];
			walkDirection.x = stickX < 1500 ? -1 : stickX > 2100 ? 1 : 0;
			walkDirection.y = stickY < 1500 ? -1 : stickY > 2500 ? 1 : 0;

			stickX = joyconR.GetStickPrecal()[0];
			stickY = joyconR.GetStickPrecal()[1];
			cameraMovement.x = stickX < 1500 ? -1 : stickX > 2800 ? 1 : 0;
			cameraMovement.y = stickY < 1000 ? -1 : stickY > 2500 ? 1 : 0;
			
			//Debug.Log("X: "+stickX+" Y:"+stickY);
		}
		else{
			joyconL = joyconMgr.GetJoycon(JoyconManager.JoyconType.left);
			joyconR = joyconMgr.GetJoycon(JoyconManager.JoyconType.right);
		}
	}

	public bool isConnected(){
		return joyconL != null && joyconR != null ;
	}

	public bool isPressing(Joycon.Button b, bool left=true){
		if (!isConnected()){
			Debug.Log("joycon not found");
			return false;
		}
		return left? joyconL.GetButton(b) : joyconR.GetButton(b);
	}

	public bool isPressed(Joycon.Button b, bool left=true){
		if (!isConnected()){
			Debug.Log("joycon not found");
			return false;
		}
		return left? joyconL.GetButtonUp(b) : joyconR.GetButtonUp(b);
	}

	public bool isRunning(){
		if (!isConnected()){
			Debug.Log("joycon not found");
			return false;
		}
		return isPressing(Joycon.Button.SHOULDER_2,true);
	}

}
