using System;
using System.Collections.Generic;

namespace WS
{
    [ObjectSystem]
    public class ProtoManagerAwake : AwakeSystem<ProtoManager>
    {
        public override void Awake(ProtoManager self)
        {
            self.Awake();
        }
    }

    ///<summary>协议管理</summary>
    public class ProtoManager : WSComponent
    {

        private readonly Dictionary<byte, IProto> ReceiveProto = new Dictionary<byte, IProto>();
        private readonly Dictionary<byte, IProto> SendProto = new Dictionary<byte, IProto>();
        public void Awake()
        {
            LoadProto(typeof(ReceiveProtoAttribute), dic: ReceiveProto);
            LoadProto(typeof(SendProtoAttribute), dic: SendProto);
        }

        ///<summary>加载协议</summary>
        private void LoadProto(Type type, Dictionary<byte, IProto> dic = null, Dictionary<byte, Type> tdic = null)
        {
            List<Type> types = Game.EventSystem.GetTypes(type);
            for (int i = 0; i < types.Count; i++)
            {
                object[] attrs = types[i].GetCustomAttributes(type, false);
                if (attrs.Length == 0)
                {
                    continue;
                }
                WSComponent obj = ComponentFactory.CreateWithParent(types[i], this);
                IProto proto = (IProto)obj;
                if (proto == null)
                {
                    continue;
                }
                dic.Add(proto.Opcode, proto);
            }
        }

        ///<summary>获取接收协议</summary>
        public IProto GetReceiveProto(byte opcode)
        {
            IProto proto = null;
            ReceiveProto.TryGetValue(opcode, out proto);
            return proto;
        }

        ///<summary>获取发送协议</summary>
        public IProto GetSendProto(byte opcode)
        {
            IProto proto = null;
            SendProto.TryGetValue(opcode, out proto);
            return proto;
        }

        ///<summary>释放Item</summary>
        private void ItemDispose(Dictionary<byte, IProto> dic)
        {
            foreach (var item in dic)
            {
                ProtoComponent proto = (ProtoComponent)item.Value;
                proto.Dispose();
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            ItemDispose(ReceiveProto);
            ItemDispose(SendProto);
            ReceiveProto.Clear();
            SendProto.Clear();
        }
    }
}