using System.Collections.Generic;
using System.Linq;
using Assets.Source.Misc.VFX;
using Assets.Source.Patterns.ObjectPool;
using Spine.Unity;
using UnityEngine;

public class VFXEffect : MonoBehaviour, IPoolObject, IVFX
{
    public bool AutoReleaseAfterDelay = true;
    public float ReleaseDelay = 2f;
    public List<GameObject> SpecialParts;
    public List<ParticleSystem> ParticleSystems;
    public Animator[] Animators;
    public Renderer[] Renderers;
    public ParticleSystem[] SpecialPS;
    public SkeletonAnimation[] SkeletonAnimations;

    private Vector3 _initialScale;
    private Quaternion _initialRotation;

    void Awake()
    {
        _initialScale = transform.localScale;
        _initialRotation = transform.localRotation;
    }

    void OnValidate()
    {
        ParticleSystems = GetComponentsInChildren<ParticleSystem>().ToList();
    }

#if UNITY_EDITOR
    public void OnApplyPrefab()
    {
        ParticleSystems = GetComponentsInChildren<ParticleSystem>().ToList();
    }
#endif

    public void OnSpawnFromPool()
    {
        SetPlaying(true);
        transform.localScale = _initialScale;
        transform.localRotation = _initialRotation;

        if (AutoReleaseAfterDelay)
            this.After(ReleaseDelay, this.Release);
    }

    public void OnReturnToPool()
    {
        foreach (var specialPart in SpecialParts)
            specialPart.gameObject.SetActive(true);
    }

    public void SetSpecialPartActive(int index, bool active)
    {
        SpecialParts[index].SetActive(active);
    }

    public void ReleaseAfterDelay(float? delay = null)
    {
        this.After(delay ?? ReleaseDelay, this.Release);
    }

    public void SetPlaying(bool active)
    {
        foreach (var ps in ParticleSystems)
            ps.SetPlaying(active, false);
    }

    public void Replay()
    {
        foreach (var ps in ParticleSystems)
        {
            ps.SetPlaying(false, false);
            ps.SetPlaying(true, false);
        }
    }

    void IVFX.Release()
    {
        this.Release();
    }
}
