using System;
using System.Linq;
using Sirenix.OdinInspector;
using UnityEngine;
using Object = UnityEngine.Object;

namespace VOID.Generic.Status.Effect.Visual
{
    [TypeRegistryItem("Apply VFX")]
    public class ApplyVFXEffect : BasicEffect
    {
        [InfoBox(
            "<b>" + nameof(Never) + "</b> - never will be destroyed, by this effect\n" +
            "<b>" + nameof(OnParticleSystemEnd) + "</b> - will be destroyed after longest duration of " + nameof(ParticleSystem) + "\n" +
            "<b>" + nameof(OnFixedTime) + "</b> - will be destroyed after given time in seconds"
            )]
        private enum DestroyMoment
        {
            Never,
            OnParticleSystemEnd,
            OnFixedTime
        }
        
        [SerializeField, Required] private GameObject _vfxPrefab;
        [SerializeField] private DestroyMoment _destroyMoment;
        [SerializeField, ShowIf(nameof(_destroyMoment), DestroyMoment.OnFixedTime)] private float _secondsUntilDestroy;
        
        private GameObject _vfxGameObject;
        
        public override void OnApply()
        {
            _vfxGameObject = Object.Instantiate(_vfxPrefab, forObject.transform, false);

            switch (_destroyMoment)
            {
                case DestroyMoment.Never:
                    break;
                case DestroyMoment.OnParticleSystemEnd:
                    DestroyOnDurationEnd();
                    break;
                case DestroyMoment.OnFixedTime:
                    DestroyOnFixedTime();
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        private void DestroyOnDurationEnd()
        {
            var duration = _vfxGameObject
                .GetComponentsInChildren<ParticleSystem>()
                .Select(ps => ps.main.duration)
                .Max();
            Object.Destroy(_vfxGameObject, duration);
        }

        private void DestroyOnFixedTime()
        {
            Object.Destroy(_vfxGameObject, _secondsUntilDestroy);
        }

        public override void OnEnd() {}
        public override void OnTurnSelfEnd() {}
        public override void OnTurnSelfStart() {}
        public override void OnCancel() => OnEnd();

        public override string GetSimpleDescription() => $"add visual effects: {_vfxPrefab.name}";
    }
}