using System;
using System.Diagnostics;
using LJLib.Net.SPI.Com;

namespace LJLib.Net.SPI.Server
{
    internal abstract class ExcutorBase
    {
        public abstract LJResponse Excute(ILJRequest request, object state);
    }

    internal abstract class ExcutorBase<T1, T2> : ExcutorBase
        where T1:class,ILJRequest<T2>
        where T2:LJResponse,new()
    {
        protected abstract void ExcuteInternal(T1 request, object state, T2 rslt);

        protected virtual bool PreHandle(T1 request, T2 rslt) { return true; }

        public override LJResponse Excute(ILJRequest request, object state)
        {
            T2 rslt = new T2();
            try
            {
                T1 req = request as T1;
                if (req == null)
                {
                    rslt.ErrMsg = "request不能转换成类型" + typeof(T1).Name;
                    return rslt;
                }
                if (PreHandle(req, rslt))
                {
                    ExcuteInternal(req, state, rslt);
                }
            }
            catch (Exception ex)
            {
                Trace.Write(ex.ToString());
                rslt.ErrMsg = ex.ToString();
            }
            return rslt;
        }
    }
}
