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

public enum FXID
{
    SplashSmall,    // 0
    Splash,         // 1
    Ripple,         // 2
    RippleTrail,	// 3
    Focus,          // 4
    PlayerSpawn,    // 5
    TeamUp,         // 6
    Shoot,          // 7
    ShootImpact,    // 8
    Count           // 9
}

public class FXManager : MonoBehaviourSingleton<FXManager>
{
	[Tooltip("The list of FX protos")]
	public FXObjProto[] m_fxProtos;

    [System.NonSerialized]
    public Transform m_fxParent;

    [System.NonSerialized]
    public List<FXObj> m_activeFX;

	public void OnInit()
	{
        m_activeFX = new List<FXObj>();

        foreach (var fxp in m_fxProtos)
			fxp.Init();
	}

    public void Reset()
    {
        DestroyActiveFX();

        foreach (var p in m_fxProtos)
            p.Reset();
    }

    public void DestroyActiveFX()
    {
        // the active list should contain only autodestroy effects (not managed by other scripts)
        while(m_activeFX.Count > 0)
        {
            FXObj fx = m_activeFX[0];
            Debug.Assert(fx.m_autoDestroy);
            fx.DestroyFX();
        }
    }

    /*
	public void OnUpdate () 
	{
		foreach(var fxp in m_fxProtos)
			fxp.OnUpdate();
	}
	*/

        /*
        void LooseParent(Transform parent)
        {
            foreach(var fxp in m_fxProtos)
                fxp.LooseParent(parent);
        }
        */

    public FXObjProto FindFXProto(string name)
	{
		foreach(var fxp in m_fxProtos)
			if(fxp.m_prefabFX.name == name)
				return fxp;
		return null;
	}

	public FXObj PlayFX(FXID fxid, bool activate = true)
	{
		FXObj fx = m_fxProtos[(int)fxid].InstantiateFX(activate);
		return fx;
	}

	public FXObj PlayFX(FXID fxid, Transform parent, bool activate = true)
	{
		FXObj fx = m_fxProtos[(int)fxid].InstantiateFX(parent, Vector3.zero, Quaternion.identity, activate);
		return fx;
	}

	public FXObj PlayFX(FXID fxid, Transform parent, Vector3 pos, bool activate = true)
	{
		FXObj fx = m_fxProtos[(int)fxid].InstantiateFX(parent, pos, Quaternion.identity, activate);
		return fx;
	}

	public FXObj PlayFX(FXID fxid, Vector3 pos, bool activate = true)
	{
		FXObj fx = m_fxProtos[(int)fxid].InstantiateFX(m_fxParent, pos, Quaternion.identity, activate);
		return fx;
	}

	// rotate so the forward (z) axis is aligned to dir
	public FXObj PlayFX(FXID fxid, Vector3 pos, Vector3 dir, bool activate = true)
	{
		FXObj fx = m_fxProtos[(int)fxid].InstantiateFX(m_fxParent, pos, Quaternion.FromToRotation(Vector3.forward, dir), activate);
		return fx;
	}

    // ----------------------------------------------------------------
    // Custom Play FX 
    // ----------------------------------------------------------------

    public void PlayFocus(Vector3 pos, Color color)
    {
        FXObj fx = PlayFX(FXID.Focus, pos - Vector3.up * 0.3f, Vector3.up);
        fx.SetStartColor(color);
    }
}
