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

public class MachineGun : MonoBehaviour {

	[Header("Values")]
	public float activateBlock = 2;
	public float scanRadius = 10;
	public LayerMask senseMask;
	[Space(5)]
	public bool isActivate = false;
	public float rateOfFire = 0.5f;

    [Space(5)]
    public PoweredObject power;
	public GameObject gunObject;
	public Transform firingPostition;
	public Transform bulletPrefab;

	float waitingCounter = 0;
	List<Transform> enemyList;
	Transform targetObject;
	// Use this for initialization
	void Start () {
        power = gunObject.GetComponent<PoweredObject>();
		enemyList = new List<Transform>();
		waitingCounter = rateOfFire;
	}
	
	// Update is called once per frame
	void FixedUpdate () {
		Transform enemy = GetCurrentEnemy();
		float angle = 0;
		if (enemy != null)
		{
			Vector2 position = enemy.position - gunObject.transform.position;
			angle = Mathf.Atan2(position.y, position.x) * Mathf.Rad2Deg;

			if (transform.localScale.x < 0)
			{
				angle += 180;
			}
		}

		gunObject.transform.rotation = Quaternion.RotateTowards(gunObject.transform.rotation, Quaternion.Euler(0,0,angle), Time.fixedDeltaTime * 180);

		if (isActivate == true)
		{
			if (waitingCounter >= rateOfFire)
			{
				waitingCounter -= rateOfFire;
				FireBullet();
			}
			waitingCounter += Time.fixedDeltaTime;
		}
	}

	void FireBullet()
	{
		if (bulletPrefab != null)
		{
			float angle = gunObject.transform.rotation.eulerAngles.z;
			if (transform.localScale.x < 0)
			{
				angle += 180;
			}

			BaseBullet bullet = Instantiate(bulletPrefab, firingPostition.position,  Quaternion.Euler(0,0,angle)).gameObject.GetComponent<BaseBullet>();

			if (bullet != null)
			{
				bullet.owner = gameObject;
			}
		}


	}

	Transform GetCurrentEnemy()
	{
		SensingEnemy();

		if (enemyList.Count == 0)
		{
			
			return null;
		}

		if (targetObject == null)
		{
			targetObject = enemyList[0];
		}
		else
		{
			if (enemyList.Contains(targetObject) == false)
			{
				targetObject = enemyList[0];
			}
		} 

		return targetObject;
	}

	void SensingEnemy()
	{
		Collider2D[] overlapList =  Physics2D.OverlapCircleAll(transform.position, scanRadius, senseMask);
		enemyList.Clear();
		foreach(Collider2D other in overlapList)
		{
			if (other.gameObject != gameObject)
			{
				if (enemyList.Contains(other.gameObject.transform) == false)
				{
					enemyList.Add(other.transform);
				}

			}
		}

	}

	public void Fire()
	{
    	Activate();

		Invoke("DeActivate", activateBlock);
	}

	void Activate()
	{
		isActivate = true;
	}

	void DeActivate()
	{
		isActivate = false;
	}

	public bool IsFinishCoolDown()
	{
		return isActivate == false;
	}
}
