using UnityEngine;
using System.Collections;

public class Ememy_Movment_Sc : MonoBehaviour {

	public float MaxSpeed = 10f;
	public float PassiveSpeed = 2f;
	public float EnemyRage = 20f;
	public int EnemyBody;
	public GameObject Player;
	public GameObject GlobalHealth;
    public GameObject MainCamera;
	private Vector3 tempVector;
	bool facingLeft = true;
	private int CollitionTimer;
	private Vector2 RandomPos;



	void wake()
	{
		

	}
	// Use this for initialization
	void Start () {
		Player = GameObject.Find("Player_Character");
		GlobalHealth = GameObject.Find ("Global_Object");
        MainCamera = GameObject.Find("Main Camera");
		RandomPos = transform.position;
	}
	
	// Update is called once per frame
	void Update () {

		var distance = Vector3.Distance (transform.position, Player.transform.position);

		tempVector = transform.position;


		if (EnemyRage > distance) {
			
			if (Player.GetComponent<Player_Controller> ().ActiveBody != EnemyBody && CollitionTimer < 1) {
				transform.position = (Vector2.MoveTowards (transform.position, Player.transform.position, MaxSpeed * Time.deltaTime));
					//Flipping
				if (transform.position.x < Player.transform.position.x && facingLeft) {
					Flip ();
				}
				if (transform.position.x > Player.transform.position.x && !facingLeft) {
					Flip ();
				}
			} else {
				tempVector = transform.position - Player.transform.position;
				tempVector *= 2;

				transform.position = (Vector2.MoveTowards (transform.position, tempVector + Player.transform.position, MaxSpeed * Time.deltaTime));
					//Flipping 
				if (transform.position.x < Player.transform.position.x && !facingLeft) {
					Flip ();
				}
				if (transform.position.x > Player.transform.position.x && facingLeft) {
					Flip ();
				}
			}	

		} else {
			// Random Move
			Vector2 tempVector2 = transform.position;
			if (tempVector2.Equals(RandomPos)) {
				RandomPos.x = Random.Range (-20, 20);
				RandomPos.y	= Random.Range (-15, 15);
			}

			transform.position = (Vector2.MoveTowards (transform.position, RandomPos, PassiveSpeed * Time.deltaTime));
            
		}
	}

	void FixedUpdate()
	{
		if (CollitionTimer > 0) {
			CollitionTimer--;
		}

	}
			 
		
		
			

	

	void Flip()
	{
		facingLeft = !facingLeft;
		Vector3 theScale = transform.localScale;
		theScale.x *= -1;
		transform.localScale = theScale;
	}


	void OnCollisionEnter2D(Collision2D Coll)
	{
		if (Coll.gameObject.name == "Player_Character") {
			if (Player.GetComponent<Player_Controller> ().ActiveBody == EnemyBody) {
				Destroy (gameObject);
				GlobalHealth.GetComponent<Global_Place_Sc> ().PlayerScore += 10;
			}
			else if(CollitionTimer < 1) {
				GlobalHealth.GetComponent<Global_Place_Sc> ().PlayerHealth--;
                MainCamera.GetComponent<Camera_Move_Sc>().CameraShake();
                Player.GetComponent<Player_Controller>().ActiveBody = 5;
				CollitionTimer = 15;
			
			}
		}
		
	
	}


}
