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

public enum InteractState
{
	Normal,
	SelectingTarget,
	EnteringCode,
	EnteringKeyQTE,
	Confirm,
    Die,
}

public class Player : BaseObject
{
	public float speed = 5.0f;

	public InteractState state = InteractState.Normal;

	public Missile missilePrefab;

	bool moving = false;
	Vector3 moveTarget;

	public City currentCity;
	public CityPopup currentCityPopup;

	public Vector3 targetCityPos;
	public Vector3 srcCityPos;
	public GameObject targetTipPrefab;
    public GameObject targetingTipPrefab;

	public GameObject model1;
	public GameObject model2;

    public float dieMark;
    public float recoveryTime;

	public List<GameObject> targetTips = new List<GameObject>();

	public static Player LocalPlayer
	{
		get { return Game.GetInstance().GetGameForceLocal().player; }
	}

	public EnterCodeUI entercodeUI;
	public InsertKey insertkeyUI;
	public ConfirmUI confirmUI;

	void Start()
	{
		entercodeUI = FindObjectOfType<EnterCodeUI>();
		insertkeyUI = FindObjectOfType<InsertKey>();
		confirmUI = FindObjectOfType<ConfirmUI>();
	}

	[ClientCallback]
	void Update()
	{
		if (side == 0)
		{
			model1.SetActive(true);
			model2.SetActive(false);
		}
		else
		{
			model1.SetActive(false);
			model2.SetActive(true);
		}

		if (Game.GetInstance().timeRemaing>= 90)
		    return;

		if (isLocalPlayer)
		{
			Game.GetInstance().localPlayerSide = side;
			Game.GetInstance().remotePlayerSide = 1 - side;

			if (state == InteractState.Normal)
			{	
				if (moving)
				{
					transform.position = Vector3.MoveTowards(transform.position, moveTarget, Time.smoothDeltaTime * speed);
				}

				//model1.GetComponent<Animator>().Play("KimJongEn");
				//model1.GetComponent<Animator>().Update(0.01f);
				//model2.GetComponent<Animator>().Play("Trump");
				//model2.GetComponent<Animator>().Update(0.01f);
			}
		}

		if (state == InteractState.Die)
		{
			if (Time.time - dieMark > recoveryTime)
			{
				state = InteractState.Normal;
				if (model1.GetComponent<Animator>() != null)
				{
					model1.GetComponent<Animator>().Play("KimJongEn");
					model1.GetComponent<Animator>().Update(0.01f);
				}
				if (model2.GetComponent<Animator>() != null)
				{
					model2.GetComponent<Animator>().Play("Trump");
					model2.GetComponent<Animator>().Update(0.01f);
				}
			}
		}
	}

	public override void OnStartLocalPlayer()
	{
		Debug.Log("Fucking OnStartLocalPlayer" + isClient + " pcid=" + side);

		Game.GetInstance().localPlayerSide = side;
		Game.GetInstance().remotePlayerSide = 1 - side;
	}

	public override void OnStartClient()
	{
		Debug.Log("OnStartClient" + isClient);
	}

	public void Damage(BaseObject damageSrc, Vector3 damageSourcePt, float damageAmount)
	{
		if (!alive)
			return;

        // Wait yg to complete
        state = InteractState.Die;
        dieMark = Time.time;
		entercodeUI.Hide();
		insertkeyUI.Hide();
		confirmUI.Hide();
		model1.GetComponent<Animator>().Play("KimBlack");
		model2.GetComponent<Animator>().Play("TrumpBlack");
		if (currentCityPopup != null)
			currentCityPopup.Hide();
        //Die();
    }

	public override void Die()
	{
		base.Die();
	}

	#region interaction
	
	void OnTriggerEnter2D(Collider2D other)
	{
		if (other.GetComponent<City>() != null)
		{
			SetCurrentCity(other.GetComponent<City>());
		}
	}

	void OnTriggerExit2D(Collider2D other)
	{
		if (currentCity != null && other.gameObject == currentCity.gameObject)
		{
			SetCurrentCity(null);
		}
	}

	public void OnCityClick(City c)
	{
		if (state == InteractState.Normal)
		{
			if (c.side == this.side)
			{
				moveTarget = c.transform.position;
				moving = true;
			}
		}
		else if (state == InteractState.SelectingTarget)
		{
			if (c.side != this.side)
			{
				targetCityPos = c.transform.position;
				SoundEffectManager.GetInstance().PlaySoundEffect(SoundName.LockTarget);
				EnterCode();
			}
		}
	}

	void OnMouseUpAsButton()
	{
		if (Player.LocalPlayer.state == InteractState.SelectingTarget)
		{
			if (this.side != Player.LocalPlayer.side)
			{
				Player.LocalPlayer.targetCityPos = this.transform.position;
				SoundEffectManager.GetInstance().PlaySoundEffect(SoundName.LockTarget);
				Player.LocalPlayer.EnterCode();
			}
		}
	}

	#endregion

	public void SetCurrentCity(City c)
	{
		if (currentCity != c)
		{
			if (currentCity != null)
				LeaveCity();

			currentCity = c;

			if (currentCity != null)
				EnterCity();
		}
	}

	public void EnterCity()
	{
		if (state == InteractState.Normal)
		{
			if (currentCity.hasMissile)
				CityPopup();

			srcCityPos = currentCity.transform.position;
		}
	}

	public void LeaveCity()
	{
		if (currentCityPopup != null)
			currentCityPopup.Hide();
	}

	#region launch sequence

	public void CityPopup()
	{
		if (isLocal)
		{
			GameObject obj = Instantiate<GameObject>(currentCity.popupPrefab1.gameObject);
			CityPopup popup = obj.GetComponent<CityPopup>();
			popup.Init(this, currentCity);

			currentCityPopup = popup;
		}
	}
	
	public void SelectTarget()
	{
		Debug.Log("player " + side + " select target");
		state = InteractState.SelectingTarget;

		City[] cities = FindObjectsOfType<City>();
		foreach (City c in cities)
		{
			if (c != null && c.side != this.side)
			{
				GameObject obj = Instantiate<GameObject>(targetTipPrefab);
				obj.transform.position = c.transform.position;
				obj.GetComponent<CityTargetTip>().city = c;
				targetTips.Add(obj);
			}
		}
	}

	public void EnterCode()
	{
		Debug.Log("player " + side + " enter code");
		state = InteractState.EnteringCode;

		foreach (GameObject obj in targetTips)
		{
			if (obj != null)
			{
				if (Vector3.Distance(obj.transform.position, targetCityPos) <= 0.5f)
					obj.GetComponent<CityTargetTip>().destroyCountdown = 10;
				else
					obj.GetComponent<CityTargetTip>().destroyCountdown = 0;
			}
		}
		targetTips.Clear();

		entercodeUI.Show();
	}

	public void EnterKeyQTE()
	{
		Debug.Log("player " + side + " enter key QTE");
		insertkeyUI.Show();
	}

	public void Confirm()
	{
		state = InteractState.Confirm;
		confirmUI.Show();
	}

	public void StartLaunch()
	{
		Debug.Log("player " + side + " start launch");
		state = InteractState.Normal;
        SoundEffectManager.GetInstance().PlaySoundEffect(SoundName.Lift);
		currentCity.missileStand.SetActive(false);
		currentCity.hasMissile = false;
		CmdGenerateMissile(srcCityPos, targetCityPos);
	}

	[Command]
	void CmdGenerateMissile(Vector3 startPos, Vector3 targetPos)
	{
		GameObject obj = Instantiate<GameObject>(missilePrefab.gameObject);
		obj.transform.position = startPos;
		Missile missile = obj.GetComponent<Missile>();
		missile.Init(targetPos);

        GameObject tip = Instantiate<GameObject>(targetingTipPrefab.gameObject);
        tip.transform.position = targetPos;

        NetworkServer.Spawn(obj);
        NetworkServer.Spawn(tip);

    }

	public void CancelLaunch()
	{
		state = InteractState.Normal;
	}

	#endregion

}
