using System;
using System.Linq;
using SimpleCore.Library;

namespace StandardScene.Chained
{
    /// <summary>
    /// 负责根据 Delivery 上记录的回调 key 列表，通过回调注册表统一挂载所有事件回调。
    /// </summary>
    public static class DeliveryCallbackAttacher
    {
        public static void AttachAll(ChainedDeliveryMission.Delivery d)
        {
            if (d == null) return;

            // OnStart
            foreach (var key in d.OnStartCallbackKeys.Distinct())
            {
                var cb = DeliveryCallbackRegistry.ResolveOnStart(key);
                if (cb != null) d.OnStart += cb;
                else Diagnosis.Log($"Unknown OnStart callback key: {key}", "DeliveryCallbackAttacher");
            }

            // DoneFetch
            foreach (var key in d.DoneFetchCallbackKeys.Distinct())
            {
                var cb = DeliveryCallbackRegistry.ResolveDoneFetch(key);
                if (cb != null) d.DoneFetch += cb;
                else Diagnosis.Log($"Unknown DoneFetch callback key: {key}", "DeliveryCallbackAttacher");
            }

            // DonePut
            foreach (var key in d.DonePutCallbackKeys.Distinct())
            {
                var cb = DeliveryCallbackRegistry.ResolveDonePut(key);
                if (cb != null) d.DonePut += cb;
                else Diagnosis.Log($"Unknown DonePut callback key: {key}", "DeliveryCallbackAttacher");
            }

            // DoneMission
            foreach (var key in d.DoneMissionCallbackKeys.Distinct())
            {
                var cb = DeliveryCallbackRegistry.ResolveDoneMission(key);
                if (cb != null) d.DoneMission += cb;
                else Diagnosis.Log($"Unknown DoneMission callback key: {key}", "DeliveryCallbackAttacher");
            }

            // Failed
            foreach (var key in d.FailedCallbackKeys.Distinct())
            {
                var cb = DeliveryCallbackRegistry.ResolveFailed(key);
                if (cb != null) d.Failed += cb;
                else Diagnosis.Log($"Unknown Failed callback key: {key}", "DeliveryCallbackAttacher");
            }

            // OnTerminated
            foreach (var key in d.OnTerminatedCallbackKeys.Distinct())
            {
                var cb = DeliveryCallbackRegistry.ResolveOnTerminated(key);
                if (cb != null) d.OnTerminated += cb;
                else Diagnosis.Log($"Unknown OnTerminated callback key: {key}", "DeliveryCallbackAttacher");
            }
        }
    }
}

