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

public class Shuriken : MonoBehaviour
{
    [SerializeField]
    private float m_angularVelocity = 500.0f;
    [SerializeField]
    private float m_speed = 10.0f;
    [SerializeField]
    private float m_soundSpawnRateInSeconds = 1.0f;
    private float m_soundSpawnTimer = 0.0f;

    private Spawner m_spawner;
    private bool m_freed = false;

    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;
        GetComponent<Rigidbody2D>().velocity = direction * m_speed;
    }

    // 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)
    {
        var deadlyComponent = GetComponent<Deadly>();
        if (!m_freed && (deadlyComponent.immuneObject != collider.gameObject || collider.tag == "LevelBoundary"))
        {
            m_spawner.FreeShuriken(gameObject, 0.0f, true);
            m_spawner.SpawnSound(transform.position, SoundType.Big);
            m_freed = true;
        }
    }
}
