using System;
using MadByteLabs.Foundation;
using MadByteLabs.Foundation.Sound;
using MadByteLabs.__PRODUCT__.Data;
using UnityEngine;

namespace MadByteLabs.__PRODUCT__.Core
{
    /// <summary>Owns this application's scope. Place exactly one on a root in the startup scene.</summary>
    [DisallowMultipleComponent]
    public sealed class MonoBootstrapper : MonoBehaviour
    {
        [SerializeField] private SoundConfiguration m_soundConfiguration;

        private static MonoBootstrapper s_instance;
        private ApplicationScope m_scope;
        private SessionData m_session;

        /// <summary>Gets this session's sound service after Awake. Inject it into product consumers.</summary>
        public SoundModule Sound { get; private set; }

        private void Awake()
        {
            if (s_instance != null && s_instance != this)
            {
                Debug.LogError("A product bootstrapper is already running. Removing the duplicate component.", this);
                Destroy(this);
                return;
            }

            if (transform.parent != null)
            {
                Debug.LogError("MonoBootstrapper requires a root GameObject.", this);
                enabled = false;
                return;
            }

            s_instance = this;
            DontDestroyOnLoad(gameObject);
            m_session = new SessionData();
            var soundObject = new GameObject("Sound");
            soundObject.transform.SetParent(transform, false);
            Sound = soundObject.AddComponent<SoundModule>();
            Sound.Configure(m_soundConfiguration);
            m_scope = new ApplicationScope(Sound, new SessionModule(m_session));
            try
            {
                m_scope.Initialize();
            }
            catch (Exception error)
            {
                Debug.LogException(error, this);
                enabled = false;
            }
        }

        private void OnApplicationPause(bool isPaused)
        {
            if (m_session != null && enabled)
            {
                m_session.SetPaused(isPaused);
            }
        }

        private void OnDestroy()
        {
            if (s_instance != this)
            {
                return;
            }

            try
            {
                if (m_scope != null)
                {
                    m_scope.Dispose();
                }
            }
            catch (Exception error)
            {
                Debug.LogException(error, this);
            }
            finally
            {
                s_instance = null;
            }
        }
    }
}
