using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

namespace ninja
{
	[RequireComponent(typeof (NinjaMovement))]
    public class NinjaInputController : MonoBehaviour
	{
		[SerializeField] private int m_PlayerId = 0;
        [SerializeField]
        private bool m_arbitraryDirection = false;
		private NinjaMovement m_Character;
		private bool m_Jump;
		private bool m_Action;
		private bool m_ActionDone;
        private Vector3 m_lookDirection = Vector3.right;

		public void SetPlayerId(int id) {
			m_PlayerId = id;
		}

        private void Awake()
        {
			m_Character = GetComponent<NinjaMovement>();
        }

        public Vector3 lookDirection
        {
            get { return m_lookDirection; }
        }

        private void Update()
		{
			// Read the jump input in Update so button presses aren't missed.

            if (!m_Jump)
            {
				m_Jump = CrossPlatformInputManager.GetButtonDown(playerInputPrefix()+"_jump");
            }

			if (!m_Action) {
				m_Action = getActionTrigger();
				if (!m_Action) { // wait for botton release before attacking again
					m_ActionDone = false;
				}
			}
        }


        private void FixedUpdate()
        {
            // Read the inputs.
			float h = CrossPlatformInputManager.GetAxis(playerInputPrefix()+"_horizontal");
            float v = CrossPlatformInputManager.GetAxis(playerInputPrefix() + "_vertical");
            m_lookDirection.Set(h, -v, 0.0f);
            
            if (m_arbitraryDirection && Mathf.Abs(h) + Mathf.Abs(v) > Mathf.Epsilon)
            {
                m_lookDirection.Normalize();
            }
            else
            {
                m_lookDirection = GetComponent<NinjaMovement>().IsFacingRight() ? Vector3.right : Vector3.left;
            }

            // Pass all parameters to the character control script.
            m_Character.Move(h, m_Jump);

			if (m_Action && !m_ActionDone) {
				m_ActionDone = true;

				int maxPrio = -1;
				IAction maxAction = null;
				IAction[] actions = GetComponents<IAction> ();
				foreach (IAction a in actions) {
					if (a.priority () > maxPrio) {
						maxPrio = a.priority ();
						maxAction = a;
					}
				}

				if (maxAction != null) {
					maxAction.doAction ();
				}

				//print ("action "+m_PlayerId);
			}


			m_Jump = false;
			m_Action = false;
        }

		private String playerInputPrefix() {
			return "P" + (m_PlayerId + 1);
		}

		private bool getActionTrigger() {
			return CrossPlatformInputManager.GetButtonDown(playerInputPrefix()+"_do");
		}
    }
}
