using FObjBase;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WSCF
{
    public abstract class Reflect_SeviceClient : WebSocketClient, IDisposable, IReflectSeviceClientCore
    {

        /// <summary>
        /// 代理对象 接口类型
        /// </summary>
        protected abstract Type InterfaceType { get; }

        /// <summary>
        /// 已经同步完成;
        /// 已经收到了 CALL_GetAllProperties, 全部属性都与服务器一致
        /// </summary>
        public bool IsSynced { get; set; }

        /// <summary>
        /// 当前 INotifyPropertyChanged 对象 引发了 PropertyChanged,  是由于 接收到数据导致的
        /// </summary>
        public bool IsInPushValue { get; set; }

        ReflectSeviceClientAssistant assistant;

        public Reflect_SeviceClient(string serverName,bool isByConnName, string addrOrConnName)
        {
            if (isByConnName == false)
            {
                base.Init(serverName, addrOrConnName);
            }
            else {
                base.InitByConnName(serverName, addrOrConnName);
            }

            assistant = new ReflectSeviceClientAssistant();
            assistant.Init(InterfaceType, this);
            assistant.SetSendEx(Send);
        }



        protected override void OnOpen()
        {
            assistant.OnOpen();
        }
        protected override void OnMessage(string msg) 
        {
            var pkgData = JsonConvert.DeserializeObject<Reflect_OBJ_INTERFACE.PkgData>(msg);
            OnMessage(pkgData);
        }
        protected virtual void OnMessage(Reflect_OBJ_INTERFACE.PkgData pkgData) 
        {
            assistant.OnMessage(pkgData);
        }

        protected override void OnClose()
        {
            assistant.OnClose();
            
        }

        protected void Call(string methodName, object parameters, AsyncCBHandler asyncDelegate, object asyncContext)
        {
            assistant.Call(methodName, parameters, asyncDelegate, asyncContext);
        }

        protected void Call(string methodName, object parameters)
        {
            Call(methodName, parameters, null, null);
        }

        protected void Call(string methodName)
        {
            Call(methodName, null, null, null);
        }
    }
}
