using UnityEngine;
using System.Collections;

public class Walker_S : MonoBehaviour {
	int eyes = 2;
	LightColour col;
	public GameObject LeftEye;
	public GameObject RightEye;
	public void SetColour(LightColour col1, LightColour col2){
		(LeftEye.GetComponent(typeof(WalkerEye)) as WalkerEye).SetColour(col1);
		(RightEye.GetComponent(typeof(WalkerEye)) as WalkerEye).SetColour(col2);
	}
	
	Vector3 center = new Vector3(989,288,1018);
	public GameObject player;	
	bool grounded = false;
	float speed = 3f;
	float jumpSpeed = 4.0f;
	float gravity = 100.0f;
	private Vector3 moveDirection = Vector3.zero;
	float rotationSpeed = 3f;
	
	float playerChaseDist = 50;
	
	void Start(){
		player = References.playerObj;
	}
	
	
	void FixedUpdate() {
		if (grounded) {
			Vector3  target;
			float dist = Vector3.Distance(player.transform.position, transform.position);
			if(dist < playerChaseDist && dist < Vector3.Distance(center, transform.position))
				target = player.transform.position;
			else
				target = center;
			
			Vector3 direction = target - transform.position; 
			direction.y = 0; 
			transform.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime); 
			transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0); 
			Vector3 forward = transform.TransformDirection(Vector3.forward); 
		    float speedModifier = Vector3.Dot(forward, direction.normalized); 
		    speedModifier = Mathf.Clamp01(speedModifier); 
		    moveDirection = forward * speed * speedModifier; 
			
			if (Random.value > 2f) {
				moveDirection.y = jumpSpeed;
			}
		}
		moveDirection.y -= gravity * Time.deltaTime;
		CharacterController controller = gameObject.GetComponent(typeof(CharacterController)) as CharacterController;
		CollisionFlags flags = controller.Move(moveDirection * Time.deltaTime);
		grounded = (flags & CollisionFlags.CollidedBelow) != 0;		
	}
	
	
	float myDamageVsPlayer = 90f;
	float myDamageVsFlower = 450f;
	public void EnterFlower(Flower_S flower){
		flower.TakeDamage(myDamageVsFlower);
		Destroy(gameObject);
	}
	
	public void EnterPlayer(PlayerTouch_S player){
		player.TakeDamage(myDamageVsPlayer);
		AIDirector.DecreaseAlive();
		Destroy(gameObject);
	}
	public AudioClip damageClip;
	public void LoseEye(){
		eyes--;
		GameObject effect = Instantiate(References.soundEffectObj, transform.position, Quaternion.identity) as GameObject;
		SoundEffect_S effect_script = effect.GetComponent(typeof(SoundEffect_S)) as SoundEffect_S;
		effect_script.SetEffect(damageClip);
		effect_script.SetVolume(100f);	
		effect_script.SetIgnoreVolume(true);
		GUIScript.AddScore(100);
		if(eyes <= 0){
			for(int i = 0; i< 15; i++){
				Instantiate(References.dieEffectObj, transform.position+new Vector3(Random.value*20-10, Random.value*20-10, Random.value*20-10), Quaternion.identity);
			}
			GUIScript.AddScore(200);
			AIDirector.DecreaseAlive();
			Destroy(gameObject);
		}
	}
	
}
