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

public class Laser : Weapon {

    public float dps;

    public LayerMask hitMask;

    public GameObject hitEffect;

    public float effectInterval;

    float lastEffectDelay;

    LineRenderer line;

    ParticleSystem particles;

    AudioSource audioSource;

	// Use this for initialization
	void Start () {
        line = muzzle.GetComponent<LineRenderer>();
        line.enabled = false;
        particles = muzzle.GetComponent<ParticleSystem>();
        particles.Stop();
        audioSource = GetComponent<AudioSource>();
        lastEffectDelay = 0;
	}

    protected override void Fire()
    {
        if (lastEffectDelay > 0)
            lastEffectDelay -= Time.deltaTime;

        if (!audioSource.isPlaying)
            audioSource.Play();
        if (!particles.isPlaying)
            particles.Play();
        line.enabled = true;
        line.widthMultiplier = 0.16f - Mathf.Sin(Time.time * 10f) * 0.05f;
        Ray ray = new Ray(muzzle.position, muzzle.forward);
        RaycastHit[] hits = Physics.RaycastAll(ray, 14, hitMask);

        Monster enemy = null;

        HashSet<Monster> hitMonsters = new HashSet<Monster>();

        bool enemyHit = false;

        if (hits != null && hits.Length > 0)
        {
            for (int i = 0; i < hits.Length; i++)
            {
                enemy = hits[i].collider.GetComponentInParent<Monster>();
                if (enemy != null && !hitMonsters.Contains(enemy))
                {
                    enemy.TakeDamage(dps * Time.deltaTime);
                    hitMonsters.Add(enemy);

                    if (lastEffectDelay <= 0)
                    {
                        GameObject effect = GameObject.Instantiate(hitEffect, hits[i].point, Quaternion.identity);
                        GameObject.Destroy(effect, effectInterval * 2f);
                    }
                    enemyHit = true;
                }
            }
        }

        if (enemyHit && lastEffectDelay <= 0)
            lastEffectDelay = effectInterval;

        ammo -= Time.deltaTime * 100f;
    }

    protected override void DontFire()
    {
        line.enabled = false;
        audioSource.Stop();
        particles.Stop();
        particles.Clear();
    }
}
