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

public class Rail : MonoBehaviour {

	public Image handle;

	public Sprite handleSprite;
	public Transform spawnPosition;
	public Transform destroyPosition;
	public Image successZone;

	List<Image> handles = new List<Image>();

	List<Image> falseHandles = new List<Image>();

	int shouldGenerateCount = 0;
	int shouldGenerateFalseCount = 0;

	int fixedCounter;


    readonly Dictionary<KeyCode, CharacterAnimationController.AnimationType> _keyCodeToAnimationMap = new Dictionary<KeyCode, CharacterAnimationController.AnimationType>()
    {
        {KeyCode.Q, CharacterAnimationController.AnimationType.HandsUp},
        {KeyCode.W, CharacterAnimationController.AnimationType.Wave},
        {KeyCode.E, CharacterAnimationController.AnimationType.Kiss},
        {KeyCode.R, CharacterAnimationController.AnimationType.ChestBeat},
        {KeyCode.T, CharacterAnimationController.AnimationType.Salut},
        //to remove
        {KeyCode.UpArrow, CharacterAnimationController.AnimationType.Idle},
        {KeyCode.LeftArrow, CharacterAnimationController.AnimationType.Idle},
        {KeyCode.RightArrow, CharacterAnimationController.AnimationType.Idle}


    };


	List<Image> destroyed = new List<Image> ();
	// Update is called once per frame
	void Update () 
	{
		destroyed.Clear ();
		foreach (var itHandle in handles) 
		{
			if (itHandle.transform.position.y < destroyPosition.position.y) {
				destroyed.Add (itHandle);
				Destroy (itHandle.gameObject);

				if (falseHandles.Contains (itHandle) == false) {
					LifeController.instance.MoveFailed ();
					//Debug.Log ("handle missed");
					ParticlesController.instance.PlayParticleFailure (itHandle.transform.position);
					AudioContainer.instance.failureTap2.Play ();
                    ScoreController.instance.OnMissedHit();
                    WomboComboShower.instance.ShowMiss();
                    ParticlesController.instance.PlayParticleFailure (itHandle.transform.position);
                }
                else {
					//Debug.Log ("flase handle missed");
				}
			}
		}
		foreach (var itGo in destroyed) {
			if (falseHandles.Contains (itGo)) {
				falseHandles.Remove (itGo);
			}
			if (handles.Contains (itGo)) {
				handles.Remove (itGo);
			}
		}
	}

	public bool HasHandles()
	{
		return handles.Count != 0 && falseHandles.Count != 0;
	}

	public void SpawnHandle()
	{
		shouldGenerateCount++;
	}

	public void SpawnFalseHandle()
	{
		shouldGenerateFalseCount++;
	}


	void FixedUpdate()
	{
		fixedCounter++;
		if (fixedCounter > 10)
			return;
		fixedCounter = 0;



		for (int i = 0; i < shouldGenerateCount; i++) 
		{
			var h = Instantiate (handle) as Image;
			h.transform.position = spawnPosition.position;
			h.transform.parent = this.transform;
			h.rectTransform.localScale = Vector2.one;
			h.sprite = handleSprite;
			handles.Add(h);
		}
		shouldGenerateCount = 0;

		for (int i = 0; i < shouldGenerateFalseCount; i++) 
		{
			var h = Instantiate (handle) as Image;
			h.transform.position = spawnPosition.position;
			h.transform.parent = this.transform;
			h.rectTransform.localScale = Vector2.one;
			h.sprite = handleSprite;
			handles.Add(h);
			falseHandles.Add (h);
		}
		shouldGenerateFalseCount = 0;
	}


	public void ProcessKeyPress()
	{
		Image closestHandle = GetClosestHandle ();
		if (closestHandle == null)
		{
			LifeController.instance.MoveFailed ();
            ScoreController.instance.OnHitNothing();
			AudioContainer.instance.failureTap2.Play ();
            //Debug.Log("no handles");
			return;
		}



		float score = CheckIntersection (closestHandle);

		//get scores
		if ( score > 0) 
		{
			if (falseHandles.Contains (closestHandle) == false) {
				if (score == 1f) {
					ParticlesController.instance.PlayParticleSuccess (closestHandle.transform.position);
					ScoreController.instance.OnPerfectHit ();
					LifeController.instance.MoveSuccedded ();
					ParticlesController.instance.PlayParticleLifeGain ();
                    
				} else {
					ParticlesController.instance.PlayParticleSuccess (closestHandle.transform.position);
					ScoreController.instance.OnNormalHit(score);
                    WomboComboShower.instance.ShowHitPercent(score);
                }
				handles.Remove (closestHandle);
				AudioContainer.instance.succesTap.Play ();
				//Debug.Log ("score: " + score);
			} else {
				LifeController.instance.MoveFailed ();
                ScoreController.instance.OnBadResult();
                WomboComboShower.instance.ShowMiss();
                
                ParticlesController.instance.PlayParticleFailure (closestHandle.transform.position);
                //Debug.Log("hit wrong handle");
				handles.Remove(closestHandle);
				falseHandles.Remove (closestHandle);
				AudioContainer.instance.failureTap.Play ();
			}
			Destroy (closestHandle.gameObject);
		} 
		else 
		{
			LifeController.instance.MoveFailed ();
            WomboComboShower.instance.ShowMiss();
            //Debug.Log ("miss");
            //miss
        }

	}

	//in percents
	float CheckIntersection(Image image)
	{
		float height = 100;//image.rectTransform.rect.height;

		float imageYmax = image.transform.localPosition.y + height / 2;
		float imageYmin = image.transform.localPosition.y - height / 2;


		float scsYmax = successZone.transform.localPosition.y + successZone.rectTransform.rect.height / 2;
		float scsYmin = successZone.transform.localPosition.y - successZone.rectTransform.rect.height / 2;

		if (imageYmin > scsYmax || imageYmax < scsYmin)
			return 0;
		
		float result = 1f - (Mathf.Clamp ((imageYmax - scsYmax), 0f, height) +
			Mathf.Clamp (( scsYmin - imageYmin), 0f, height))/ height;

		Debug.Log (result);
		return result;
	}

	Image GetClosestHandle()
	{
		float currentDistance = 100000;

		Image result = null;
		foreach (var itHandle in handles) 
		{
			float delta = itHandle.transform.position.y - successZone.transform.position.y;
			if (delta < currentDistance && delta > -40 ) { //get size of the zone
				result = itHandle;
				currentDistance = delta;
			}
		}
		return result;
	}
}
