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

public class FlashGrenade : MonoBehaviour {
    [SerializeField]
    private float m_angularVelocity = 150.0f;
    [SerializeField]
    private float m_forceMagnitude = 15.0f;
    [SerializeField]
    private float m_soundSpawnRateInSeconds = 1.0f;
    private float m_soundSpawnTimer = 0.0f;
    [SerializeField]
    private float m_angle = Mathf.PI * 0.25f;
    [SerializeField]
    private GameObject m_userOfGrenade;

    private Spawner m_spawner;
    private bool m_freed = false;

    public GameObject userOfGrenade
    {
        set { m_userOfGrenade = value; }
        get { return m_userOfGrenade; }
    }

    public void Awake()
    {
        m_spawner = Util.Find<Spawner>("Spawner");
        Debug.Assert(GetComponent<Rigidbody2D>());
    }

    // Use this for initialization
    void Start()
    {
    }

    public void Shoot(Vector3 direction)
    {
        m_freed = false;
        m_soundSpawnTimer = m_soundSpawnRateInSeconds;
        GetComponent<Rigidbody2D>().angularVelocity = m_angularVelocity;
        Vector2 forceDirection = new Vector2(Mathf.Cos(m_angle), Mathf.Sin(m_angle));
        if (Vector3.Dot(direction, Vector3.right) < 0.0f)
            forceDirection = new Vector2(-forceDirection.x, forceDirection.y);

        GetComponent<Rigidbody2D>().velocity.Set(0.0f, 0.0f);
        GetComponent<Rigidbody2D>().AddForce(forceDirection * m_forceMagnitude, ForceMode2D.Force);
    }

    // Update is called once per frame
    void Update()
    {
        //m_soundSpawnTimer += Time.deltaTime;
        //if (m_soundSpawnTimer > m_soundSpawnRateInSeconds)
        //{
        //    m_spawner.SpawnSound(transform.position, SoundType.Medium);
        //    m_soundSpawnTimer = 0.0f;
        //}


    }

    public void OnTriggerEnter2D(Collider2D collider)
    {
        if (!m_freed && collider.gameObject != m_userOfGrenade)
        {
            m_spawner.FreeGrenade(gameObject, 0.0f, true);
            m_spawner.SpawnSound(transform.position, SoundType.Big);
            var explosion = m_spawner.SpawnGrenadeExplosion(transform.position);
            m_freed = true;
        }
    }
}
