using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Seayoo.ComboSDK.Windows.Account
{
    public class __RegisterMediator : MonoBehaviour
    {
        private MonoBehaviour target;
        private IMediator mediator;
        void Awake()
        {
            RegistTarget();
        }

        void OnDestroy()
        {
            if (mediator != null)
            {
                mediator.OnRemove();
                target = null;
                mediator = null;
            }
        }

        void RegistTarget()
        {
            if (target == null)
            {
                target = FindScriptWithRegisterAttr();
                mediator = RegisterAttribute.Create(target);
            }
            mediator.OnRegister();
        }

        private MonoBehaviour FindScriptWithRegisterAttr()
        {
            MonoBehaviour result = null;
            var results = new List<MonoBehaviour>();
            this.GetComponents<MonoBehaviour>(results);
            foreach (var script in results)
            {
                var attributes = script.GetType().GetCustomAttributes(true);
                foreach (Attribute attr in attributes)
                {
                    if (attr is RegisterAttribute)
                    {
                        result = script;
                        break;
                    }
                }
            }
            return result;
        }
    }
}
