using UnityEngine;
using System.Collections;
using System;

public class EnemyBehaviour : MonoBehaviour {
	
	private const float SPEED = 1.0f;
	
	float moveRemaining = 0;
	int versor = -1;
	bool isAttacking = false;
	
	float savedMoveRemaining = 0;
	int savedVersor = 0;
	int frameCounter = 0;
	
	GameObject bullet;
	GameObject player1;
	GameObject player2;

	// Use this for initialization
	void Start () {
		player1 = GameObject.Find("Player1");
		player2 = GameObject.Find("Player2");
		bullet = GameObject.Find("Bullet");
		this.gameObject.renderer.enabled = false;
	}
	
	// Update is called once per frame
	void Update () {
		if (this.gameObject.renderer.enabled) {
			float t = Time.time;
			if (!isAttacking){
				float delta = Time.deltaTime * SPEED;
				Vector3 vec = new Vector3 (0, -delta*versor, 0);
				vec = Vector3.ClampMagnitude(vec, delta);
				//vec = vec * Referee.LevelSpeed;
				this.transform.Translate(vec);
				if (t > moveRemaining){
					versor = versor * -1;
					moveRemaining = t+0.5f;
				}
				if (checkProximity()) {
					isAttacking = true;
					savedMoveRemaining = moveRemaining-t;
					if (savedMoveRemaining < 0)
						savedMoveRemaining = 0;
					savedVersor = versor;
					moveRemaining = t + 3f;
				}
			}
			else {
				if (t < moveRemaining){
					frameCounter++;
					if (frameCounter % 20 == 0)
						Instantiate(bullet, this.transform.position+(new Vector3(-0.45f,0.1f,0)), Quaternion.identity);
				}
				else {
					isAttacking = false;
					frameCounter = 0;
					moveRemaining = savedMoveRemaining;
					versor = savedVersor;
				}
			}
		}
	}
	
	bool checkProximity() {
		if ((player1.transform.position.y < this.gameObject.transform.position.y+0.1 &&
			player1.transform.position.y > this.gameObject.transform.position.y-0.1) ||
		    (player2.transform.position.y < this.gameObject.transform.position.y+0.1 &&
			player2.transform.position.y > this.gameObject.transform.position.y-0.1))
			return true;
		return false;
	}
	
}
