using System;
using System.Collections.Generic;
using LJLib.Net.SPI.Com;

namespace LJLib.Net.SPI.Server
{
    public abstract class LJServerBase : ILJServer
    {
        public delegate LJResponse DHandle(ILJRequest request, object state); // 委托声明
        protected Dictionary<string, DHandle> handlers = new Dictionary<string, DHandle>(); // 缓存所有处理
        protected Dictionary<string, Type> requestTypes = new Dictionary<string, Type>();

        public LJResponse DoExcute(ILJRequest request, object state)
        {
            if (!handlers.ContainsKey(request.GetApiName()))
            {
                throw new Exception("接口未定义:" + request.GetApiName().ToString());
            }
            DHandle handler = handlers[request.GetApiName()];// 必成从缓存读取
            if (handler == null)
            {
                throw new Exception("接口未定义:" + request.GetApiName().ToString());
            }
            return handler(request, state);
        }

        public Type GetRequestType(string apiName)
        {
            if (requestTypes.ContainsKey(apiName))
            {
                return requestTypes[apiName];
            }
            else
            {
                throw new Exception("接口未定义:" + apiName);
            }
        }

        public void AddMap(string apiName, Type requestType, DHandle handler)
        {
            requestTypes[apiName] = requestType;
            handlers[apiName] = handler;
        }
    }
}