using System;
using System.Collections.Generic;
using Assets.Source.Core.Interfaces;
using Assets.Source.Patterns;
using Assets.Source.Settings;
using UnityEngine;

namespace Assets.Source.Core.Managers
{
    public class ScriptableWorkersController : Singleton<ScriptableWorkersController>
    {
        private static Dictionary<Type, ScriptableObject> _workerScriptableObjects = new Dictionary<Type, ScriptableObject>();

        public static List<IScriptableWorker> Workers { get; } = new List<IScriptableWorker>();

        protected override void Init()
        {
            InitWorkers(true);
        }

        private static void InitWorkers(bool callInit)
        {
            Workers.Clear();
            _workerScriptableObjects.Clear();
            foreach (var worker in CoreSettings.Asset.CommonScriptableWorkers)
            {
                _workerScriptableObjects.Add(worker.GetType(), worker);
                Workers.Add(worker as IScriptableWorker);
            }

            if (!callInit)
                return;

            foreach (var worker in CoreSettings.Asset.CommonScriptableWorkers)
            {
                var runtimeSO = worker as IScriptableWorker;
                runtimeSO?.ClearContent();
            }
            foreach (var worker in CoreSettings.Asset.CommonScriptableWorkers)
            {
                var runtimeSO = worker as IScriptableWorker;
                runtimeSO?.Init();
            }
        }

        public static T Get<T>() where T : ScriptableObject
        {
            //if (Instance == null)
            //    return null;
            if (!Application.isPlaying && _workerScriptableObjects.Count != CoreSettings.Asset.CommonScriptableWorkers.Length)
                InitWorkers(false);
            return (T)_workerScriptableObjects[typeof(T)];
        }
    }
}
