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

public class PoolableType : MonoBehaviour
{
    #region Public Members

    // Whether to destroy when the time is up ( if enabled )
    public bool DestroyOnComplete;

	// Whather to Despawn after a set time
    public bool AutoDespawn;

    // The length of time before despawning
    public float DespawnTime;
	
	// The type that this object is 
    public PoolType PooledType;

    #endregion

    #region Private Members

    // The cached transform of the game object
    private Transform m_transform;

    // List of the particle systems in this effect if it has any
    private List<ParticleSystem> m_particleSystems;

    #endregion

    #region Startup

    public void Initialize()
    {
        m_transform = transform;
        SetupType();
    }

    private void SetupType()
    {
        switch (PooledType)
        {
            case PoolType.ParticleEffect:
            {
                CacheParticleSystems();
                break;
            }
        }
    }

    private void CacheParticleSystems()
    {
        m_particleSystems = new List<ParticleSystem>();

        foreach (var system in m_transform.GetComponents<ParticleSystem>())
        {
            m_particleSystems.Add(system);
        }
    }

    #endregion

    #region Public Methods

    public void Spawn(Vector3 position)
    {
        gameObject.SetActive(true);
        m_transform.position = position;

        if (PooledType == PoolType.ParticleEffect)
        {
            foreach (var system in m_particleSystems)
            {
                system.Play();
            }

            if (AutoDespawn)
            {
                StartCoroutine(WaitForCompletion());
            }
        }
    }

    public void Despawn()
    {
        gameObject.SetActive(false);
        m_transform.position = Vector3.zero;
    }

    private IEnumerator WaitForCompletion()
    {
        yield return new WaitForSeconds(DespawnTime);

        if (DestroyOnComplete)
        {
            Destroy(gameObject);
        }
        else
        {
            gameObject.SetActive(false);
        }
    }

    #endregion

    #region private Helpers

    private Vector3 ConvertPosition(Vector3 position)
    {
        var pos = Camera.mainCamera.WorldToViewportPoint(position);
        // var pos2 = m_uiCamera.ViewportToWorldPoint(pos);
        return pos;
    }


    #endregion
}
