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

public class Weapon : MonoBehaviour {

    public float Range = 5f;
    public float Radius = 1f;

    public float fireTime = 1f;

    public LayerMask collisionMask;
    private bool canFire = true;

    public int weaponType = 1;

    public ParticleSystem prefabRed;
    public ParticleSystem prefabBlue;
    private Player player;
    private Animator anim;
	// Use this for initialization
	void Start () {
        player = GetComponent<Player>();
        anim = player.GetComponent<Animator>();
	}
	
	// Update is called once per frame
	void Update () {

	}

    public void Fire(Vector2 dir)
    {
        StartCoroutine(FireWeapon(dir));
    }
    IEnumerator FireWeapon(Vector2 dir)
    {
        if (canFire && anim.GetBool("kumanda"))
        {
            canFire = false;
            Debug.Log("Firing!");

            ParticleSystem ps;

            if (weaponType == 1) 
                ps = Instantiate(prefabRed, prefabRed.transform.position, Quaternion.identity);
            else
                ps = Instantiate(prefabBlue, prefabBlue.transform.position, Quaternion.identity);
            
            var sh = ps.shape;

            sh.position = player.spriteRenderer.flipX ? Vector3.left : Vector3.right;
            sh.rotation = new Vector3(0, 0, player.spriteRenderer.flipX ? 180 : 0);
            var vh = ps.velocityOverLifetime;
            vh.x  = player.spriteRenderer.flipX ? -10 : 10;
            ps.Play();
            RaycastHit2D[] hits = Physics2D.CircleCastAll(transform.position, Radius,dir,Range, collisionMask);
            foreach (var hit in hits)
            {
                if (hit.transform == transform) continue;

                if (weaponType == 1) 
                    hit.transform.GetComponent<Agent>().SetState(AgentState.Aggressive);
                else
                {
                    var agent = hit.transform.GetComponent<Agent>();
                    agent.target = transform;
                    agent.SetState(AgentState.Follow);
                }
            

                //Debug.Log(transform.name + " hit " + hit.transform.name);
            }
            Debug.DrawLine(transform.position, transform.position + new Vector3(dir.x,dir.y,0) * Range, Color.green, fireTime);
            yield return new WaitForSeconds(fireTime);
            Destroy(ps.gameObject);
            canFire = true;

        }
    }

    void OnParticleCollision(GameObject other)
    {
        if (other.transform == transform) return;
        Debug.Log(transform.name + " hit " + other.transform.name);


    }
}
