using System.Linq;
using JetBrains.Annotations;
using UnityEngine;

namespace JohnsonUtils.Common
{
    public class SettingsSystem : PersistentSingleton<SettingsSystem>
    {
        private const string SETTINGS_FOLDER_PATH = "Settings";

        [PublicAPI]
        public static GameSettings GameSettings => Instance.GameSetting;

        private GameSettings _gameSetting;
        private GameSettings GameSetting => _gameSetting;

        protected override void Awake()
        {
            base.Awake();

            LoadSettings(out _gameSetting);
        }

        [PublicAPI]
        private void LoadSettings<T>(out T memberToInitialize) where T : ScriptableObject
        {
            T[] loadedSettingsList = Resources.LoadAll<T>(SETTINGS_FOLDER_PATH);

            Debug.Assert(loadedSettingsList.Any(),
                $"An object of type {typeof(T).Name} should be in the folder {SETTINGS_FOLDER_PATH}");
            if (loadedSettingsList.Length > 1)
                Debug.LogWarning(
                    $"More than one object of type {typeof(T).Name} was found in the folder {SETTINGS_FOLDER_PATH}. Taking the first one.");

            memberToInitialize = loadedSettingsList.First();
        }

        [PublicAPI]
        private void LoadAllSettings<T>(out T[] memberToInitialize) where T : ScriptableObject
        {
            T[] loadedSettingsList = Resources.LoadAll<T>(SETTINGS_FOLDER_PATH);

            Debug.Assert(loadedSettingsList.Any(),
                $"An object of type {typeof(T).Name} should be in the folder {SETTINGS_FOLDER_PATH}");

            memberToInitialize = loadedSettingsList;
        }
    }
}