using UnityEngine;
using System.Collections;

public class Target : MonoBehaviour {

    public int m_idPlayer;

    public GameManager m_gameManager;
    private LensFlare m_lensFlare;

    private bool m_blink = false;
    private float m_blinkTime = 0.0f;
    private float m_blinkMaxTime = 2.0f;

    private float m_blinkPower;
    private float m_blinkPowerMax = 2.5f;
    private const float m_blinkStep = 0.1f;

    private bool m_blinkRise = false;

	// Use this for initialization
	void Start () {
        m_blinkTime = m_blinkMaxTime;
        m_lensFlare = GetComponent<LensFlare>();

        m_blinkPower = 0.0f;
    }
	
	// Update is called once per frame
	void Update () {
	    
        if(m_blink)
        {
            m_blinkTime -= Time.deltaTime;

            if(m_blinkRise)
            {
                m_blinkPower += m_blinkStep;

                if (m_blinkPower >= m_blinkPowerMax)
                    m_blinkRise = false;
            }
            else
            {
                m_blinkPower -= m_blinkStep;

                if (m_blinkPower <= 0.0f)
                    m_blinkRise = true;
            }

            m_lensFlare.brightness = m_blinkPower;

            if (m_blinkTime <= 0.0f)
            {
                m_blink = false;
                m_blinkTime = m_blinkMaxTime;
                m_lensFlare.brightness = 0.0f;
            }

        }
	}

    void OnCollisionEnter2D(Collision2D coll)
    {

    }

    void OnTriggerEnter2D(Collider2D coll)
    {
        if (coll.gameObject.tag == "Peon")
        {
            Peon peon = coll.gameObject.GetComponent<Peon>();

            if (peon.m_idMaster == m_idPlayer)
            {
                //Kill the peon + Add point
                m_gameManager.IncrementScore(m_idPlayer);
                Blink(m_idPlayer);

                peon.Reset();
            }
        }
    }

    void OnTriggerStay2D(Collider2D coll)
    {
        if (coll.gameObject.tag == "Peon")
        {
            Peon peon = coll.gameObject.GetComponent<Peon>();

            if (peon.m_idMaster == m_idPlayer)
            {
                //Kill the peon + Add point
                m_gameManager.IncrementScore(m_idPlayer);
                Blink(m_idPlayer);

                peon.Reset();
            }
        }
    }

    public void Blink(int idPlayer)
    {
        if(idPlayer == m_idPlayer)
        {
            m_blink = true;
        }
    }
}
