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

public class PhysicBall : MonoBehaviour {

	[SerializeField]Score score0, score1;
	Rigidbody2D rb;
	[SerializeField]GameObject catchedTower;

	private List<GameObject> blueCatchedTower;
	private List<GameObject> redCatchedTower;

	SpriteRenderer spriteRenderer;
	bool isBlue;
	[SerializeField] TrailRenderer blueTrail, redTrail;

	public bool isAI;

	public Text redTowers;
	public Text blueTowers;

	private int nonPlayerHits;

	[SerializeField]GameObject winMessage;
	[SerializeField]Text winText;

    public AudioClip goal;
    public AudioClip bounce;
    public AudioClip turretCaptured;
    public AudioClip turretPlaced;

    public SpriteRenderer blueSprite;
    public SpriteRenderer redSprite;

    public Sprite attractSprite;
    public Sprite repelSprite;

    private bool gameEnded;

	void Start () {
		spriteRenderer = GetComponent<SpriteRenderer> ();
		rb = GetComponent<Rigidbody2D> ();
		TowerGameController.instance.AddBall (GetComponent<Rigidbody2D> ());

		blueCatchedTower = new List<GameObject> ();
		redCatchedTower = new List<GameObject> ();

		GetComponent<Rigidbody2D> ().AddForce (new Vector2 (10, 0), ForceMode2D.Impulse);
		nonPlayerHits = 0;
        gameEnded = false;

    }


    void ReleaseTower(List<GameObject> colorList, Text textToReplace)
    {
        GameObject newCatchedTower = colorList[0];
        newCatchedTower.transform.position = transform.position - new Vector3(rb.velocity.x, rb.velocity.y).normalized * 0.6f;
        if (TowerGameController.instance.AddTower(newCatchedTower))
        {
  


            colorList.RemoveAt(0);
            newCatchedTower.SetActive(true);

            //newCatchedTower.GetComponent<Tower> ().setBlue (isBlue);

            newCatchedTower = null;
            textToReplace.text = colorList.Count.ToString();
            PlaySound(turretPlaced);
        }
    }

	void Update(){
		//if (catchedTower != null) {
			if (Input.GetKeyDown ("left") && isBlue) {
				if (blueCatchedTower.Count > 0) {
                    ReleaseTower(blueCatchedTower, blueTowers);
                }
			}
			if (Input.GetKeyDown ("a") && !isBlue) {

				if (redCatchedTower.Count > 0) {
                    ReleaseTower(redCatchedTower, redTowers);
				}
		
			}

            if(redCatchedTower.Count > 0)
            {
                if (redCatchedTower[0].GetComponent<Tower>().isBlue())
                {
                    redSprite.sprite = repelSprite;
                }
                else
                {
                    redSprite.sprite = attractSprite;
                }
            }
            else
            {
                redSprite.sprite = null;
            }

            if (blueCatchedTower.Count > 0)
            {
                if (blueCatchedTower[0].GetComponent<Tower>().isBlue())
                {
                    blueSprite.sprite = repelSprite;
                }
                else
                {
                    blueSprite.sprite = attractSprite;
                }
            }
            else
            {
                blueSprite.sprite = null;
            }

        if (gameEnded)
        {
            rb.velocity = new Vector3(0, 0, 0);
            if (Input.GetKeyDown(KeyCode.Return))
            {
                WavongSceneManager.BackToMainMenu();
            }
        }
        //}
    }

	void FixedUpdate(){
        /*
       rb.AddForce (new Vector2 (-rb.velocity.y, rb.velocity.x).normalized * 20f * Mathf.Sin (6f * Time.time));
       
        */
      if (isBlue)
          rb.AddForce (Vector2.left * 2f);
      else
          rb.AddForce (Vector2.right * 2f);

      
    }

    void TurnTrailOn(){
		if(isBlue)
			blueTrail.time = 3;
		else
			redTrail.time = 3;
	}

	void OnCollisionEnter2D(Collision2D c){
		if (c.gameObject.CompareTag ("LoseArea")) {
			c.gameObject.GetComponent<LoseArea> ().player.BallIn ();
			TowerGameController.instance.IncreasePower ();
			blueTrail.time = 0;
			redTrail.time = 0;
			Camera.main.DOShakePosition (0.3f, 0.5f, 50, 90f).OnComplete(TurnTrailOn);

			if (transform.position.x > 0f)
				score0.IncreaseScore ();
			else
				score1.IncreaseScore ();

			if (score0.score == 11 && (score0.score - score1.score) > 2) {
				winMessage.SetActive (true);
				winText.text = "Red Player Wins";
				winText.color = Color.red;
				TowerGameController.instance.RemoveBall (GetComponent<Rigidbody2D> ());
                gameEnded = true;

               // Destroy(gameObject);
			} else if (score1.score == 11 && (score1.score - score0.score) > 2) {
				winMessage.SetActive (true);
				winText.text = "Blue Player Wins";
				winText.color = Color.blue;
				TowerGameController.instance.RemoveBall (GetComponent<Rigidbody2D> ());
                gameEnded = true;

               // Destroy(gameObject);
            } else {
                
                if (transform.position.x > 0f)
                {
                    spriteRenderer.color = new Color(0f, 0f, 0.78f, 1f);
                    isBlue = true;

   
                }
                else
                {
                    spriteRenderer.color = new Color(0.78f, 0f, 0.0f, 1f);
                    isBlue = false;

                    
                }
                   

                transform.position = Vector3.zero;
				GetComponent<Rigidbody2D> ().mass = 0.9f;
				nonPlayerHits = 0;

               

            }
            PlaySound(goal);
		} else if (c.gameObject.CompareTag ("Ball")) {
			c.gameObject.GetComponent<Rigidbody2D> ().AddForce (-c.contacts [0].normal * gameObject.GetComponent<Rigidbody2D> ().velocity.magnitude, ForceMode2D.Impulse);
		} else if (c.gameObject.CompareTag ("Player")) {
			if (c.gameObject.name == "Player1") {
				spriteRenderer.color = new Color (0f, 0f, 0.78f, 1f);
				isBlue = true;
				blueTrail.time = 3f;
				redTrail.time = 0f;
			} else {
				spriteRenderer.color = new Color (0.78f, 0f, 0.0f, 1f);
				isBlue = false;
				blueTrail.time = 0f;
				redTrail.time = 3f;;
			}
            PlaySound(bounce);
        }else
        {
            PlaySound(bounce);
        }

		if (!c.gameObject.CompareTag ("Player") && !c.gameObject.CompareTag ("LoseArea")) {
			nonPlayerHits++;
			if (nonPlayerHits == 10) {
				//TowerGameController.instance.RedistributeTowers ();
				nonPlayerHits = 0;
			}
		}
	}

    void OnTriggerEnter2D(Collider2D c)
    {
        if (c.gameObject.CompareTag("Tower"))
        {
            c.gameObject.SetActive(false);
            TowerGameController.instance.RemoveTower(c.gameObject);
            PlaySound(turretCaptured);
            if (!isBlue)
            {
                redCatchedTower.Add(c.gameObject);
                redTowers.text = redCatchedTower.Count.ToString();
            }
            else
            {
                blueCatchedTower.Add(c.gameObject);
                blueTowers.text = blueCatchedTower.Count.ToString();
            }
            if (isAI)
            {
                Invoke("putTower", Random.Range(0.5f, 2f));
            }
        }
    }


    public bool isblue(){
		return isBlue;
	}

	public void putTower(){
		if (redCatchedTower.Count > 0) {
            ReleaseTower(redCatchedTower, redTowers);
        }
		/*
		if(!isBlue && catchedTower != null) {
			catchedTower.SetActive (true);
			catchedTower.transform.position = transform.position - new Vector3 (rb.velocity.x, rb.velocity.y).normalized * 0.6f;
			catchedTower.GetComponent<Tower> ().setBlue (isBlue);
			catchedTower = null;
		}
		*/
	}

    void PlaySound(AudioClip clip)
    {
        GetComponent<AudioSource>().clip = clip;
        GetComponent<AudioSource>().Play();
    }
}
