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

public class SoundEmitter : MonoBehaviour, ISwordAttackEvent {
    private Rigidbody2D m_rigidbody;

    [SerializeField]
    private float m_spawnRateInSeconds = 0.5f;
    private float m_elapsedTime = 0.0f;
    [SerializeField]
    private Transform m_spawnPosOnMove;
    [SerializeField]
    private float m_alphaOnMove = 0.2f;
    [SerializeField]
    private float m_disappearTimeInSeconds = 0.5f;
    private float m_disappearLerpValue = 0.0f;
    private float m_stillTime = 0.0f;
	private Color m_color;

    private Spawner m_spawner;

	public void SetColor(Color color) {
		m_color = color;
	}

    public Color color
    {
        get { return m_color; }
        set { m_color = value; }
    }

	// Use this for initialization
	void Start () {
        m_spawner = Util.Find<Spawner>("Spawner");
        m_rigidbody = GetComponent<Rigidbody2D>();
        m_spawnPosOnMove = transform.FindChild("SoundSpawnPos");
        EventUtil.Subscribe<ISwordAttackEvent>(gameObject);
    }
	
	// Update is called once per frame
	void Update () {
        bool moving = (m_rigidbody.velocity.magnitude > Mathf.Epsilon);

        if (moving && m_elapsedTime >= m_spawnRateInSeconds)
        {
            var c = GetComponent<SpriteRenderer>().color;
            GetComponent<SpriteRenderer>().color = new Color(c.r, c.g, c.b, m_alphaOnMove);

            if (m_elapsedTime >= m_spawnRateInSeconds)
            {
                if (m_spawnPosOnMove)
					m_spawner.SpawnSound(m_spawnPosOnMove.position + Vector3.forward, SoundType.Step, m_color);
                else
					m_spawner.SpawnSound(transform.position + Vector3.forward, SoundType.Step, m_color);
                m_elapsedTime = 0.0f;
            }
            m_stillTime = 0.0f;
            m_disappearLerpValue = 0.0f;
        }
        else
        {
            m_stillTime += Time.deltaTime;

            var c = GetComponent<SpriteRenderer>().color;
            if (c.a > 0.0f && m_stillTime > 0.1f)
            {
                m_disappearLerpValue += Time.deltaTime / m_disappearTimeInSeconds;
                GetComponent<SpriteRenderer>().color = new Color(c.r, c.g, c.b, Mathf.Lerp(m_alphaOnMove, 0.0f, m_disappearLerpValue));
            }
        }

        m_elapsedTime += Time.deltaTime;
	}

    public void OnSwordAttack(GameObject attacker)
    {
        if (attacker == gameObject)
            Reveal();
    }

    public void Reveal()
    {
        m_stillTime = 0.0f;
        var c = GetComponent<SpriteRenderer>().color;
        GetComponent<SpriteRenderer>().color = new Color(c.r, c.g, c.b, m_alphaOnMove);
    }
}
