using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using YooAsset;
using ET.EventType;
using System.Threading.Tasks;

namespace ET
{
    [Event]
    public class EntryLoadCfg_Client : BEvent<ET.EventType.EntryLoadCfg>
    {
        protected override async ETTask OnEvent(EntryLoadCfg args)
        {
            Dictionary<Type, byte[]> configBytes = new Dictionary<Type, byte[]>();

            HashSet<Type> configTypes = EventSystem.Instance.GetTypes(typeof(ConfigAttribute));
            foreach (Type configType in configTypes)
            {
                var op = await YooAssetProxy.GetRawFileAsync(configType.Name);
                var cfg = op.GetRawBytes();
                if (cfg != null)
                {
                    configBytes[configType] = cfg;
                    Log.Debug($"load config {configType} ok.");
                } 
                else
                {
                    Log.Error($"load config {configType} failed.");
                }
            }

            var listTasks = ListComponent<Task>.Create();
            foreach (Type type in configBytes.Keys)
            {
                byte[] oneConfigBytes = configBytes[type];
                Task task = Task.Run(() => LoadOneInThread(type, oneConfigBytes));
                listTasks.Add(task);
            }
            await Task.WhenAll(listTasks.ToArray());
            Log.Debug("register all config ok");
        }

        private void LoadOneInThread(Type configType, byte[] oneConfigBytes)
        {
            object category = SerializeHelper.Deserialize(configType, oneConfigBytes, 0, oneConfigBytes.Length);
            (category as ISingleton).Register();
            Log.Debug($"Deserialize: {configType} ok");
        }
    }
}