using System.Linq;
using UnityEngine;

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

        public static GameSettings GameSettings => Instance.GameSetting;

        private GameSettings gameSetting;
        private GameSettings GameSetting => gameSetting;

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

            LoadSettings(out gameSetting);
        }

        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();
        }

        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;
        }
    }
}