using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

using FObjBase;
using FLY.Thick.Base.IService;
using FLY.Thick.Base.OBJ_INTERFACE;
using FLY.Thick.Base.Common;
using PropertyChanged;
using Newtonsoft.Json;

namespace FLY.Thick.Base.Client
{
    /// <summary>
    /// 样品采样服务 客户代理
    /// </summary>
    [JsonObject(MemberSerialization.OptIn)]
    public class GetSampleServiceClient : FObjServiceClient, IGetSampleService
    {
        #region IGetSampleService 成员

        /// <summary>
        /// 参数:使能
        /// </summary>
        [JsonProperty]
        public bool Enable { get; set; }

        /// <summary>
        /// 参数:速度
        /// </summary>
        [JsonProperty]
        public UInt32 Velocity { get; set; }

        /// <summary>
        /// 参数:样品点范围
        /// </summary>
        [JsonProperty]
        public int Range { get; set; }


        /// <summary>
        /// 滤波窗口
        /// </summary>
        [JsonProperty]
        public int Window { get; set; }

        /// <summary>
        /// 使用%方式检查异常
        /// </summary>
        [JsonProperty]
        public bool IsCheckByPercent { get; set; } = true;
        /// <summary>
        /// 异常% 单位%
        /// </summary>
        [JsonProperty]
        public double ErrPercent { get; set; } = 2;
        /// <summary>
        /// 异常值
        /// </summary>
        [JsonProperty]
        public int ErrValue { get; set; } = 200;

        /// <summary>
        /// 样品
        /// </summary>
        [JsonProperty]
        public SampleCell[] Samples { get; set; } = new SampleCell[3];

        /// <summary>
        /// 查找公差
        /// </summary>
        [JsonProperty]
        public int Search { get; set; }

        /// <summary>
        /// 特征  相识度 0 正, 1 反
        /// </summary>
        [JsonProperty]
        public SampleFeature[] Features { get; set; } = new SampleFeature[2];


        /// <summary>
        /// 状态:从flyad7 得到的。 用于绘制图
        /// </summary>
        [JsonProperty]
        public int PosOfGrid { get; set; } = 10;

        /// <summary>
        /// 
        /// </summary>
        public void Apply()
        {
            GETSAMPLE_OBJ_INTERFACE.Pack_Params p = new GETSAMPLE_OBJ_INTERFACE.Pack_Params
            {
                enable = Enable,
                velocity = Velocity,
                range = Range,
                window = Window,
                IsCheckByPercent = IsCheckByPercent,
                ErrPercent = ErrPercent,
                ErrValue = ErrValue,
                search = Search,
                samples = from sample in Samples
                          select
                              new GETSAMPLE_OBJ_INTERFACE.Pack_Params_SampleCell()
                              {
                                  enable = sample.Enable,
                                  justForCheck = sample.JustForCheck,
                                  orgad = sample.OrgAD,
                                  position = sample.Position
                              },
                features = from feature in Features
                           select
                               new GETSAMPLE_OBJ_INTERFACE.Pack_Params_SampleFeature()
                               {
                                   enable = feature.Enable,
                                   startpos = feature.StartPos,
                                   endpos = feature.EndPos
                               }
            };

            string json = Newtonsoft.Json.JsonConvert.SerializeObject(p);

            //获取所有数据,设置推送
            CurrObjSys.SetValueEx(
                mConn, mServerID, ID,
                GETSAMPLE_OBJ_INTERFACE.SET_PARAMS,
                Misc.Converter.StringToBytes(json)
                );
        }
        #endregion

        public GetSampleServiceClient(UInt32 id) : base(id) { init(); }


        public GetSampleServiceClient(UInt32 serviceId, string connName) : base(serviceId, connName) { init(); }

        void init()
        {
            for (int i = 0; i < Samples.Count(); i++)
                Samples[i] = new SampleCell();

            for (int i = 0; i < Features.Count(); i++)
                Features[i] = new SampleFeature();
        }

        public override void ConnectNotify(IFConn from)
        {
            base.ConnectNotify(from);
            if (from.IsConnected)
            {
                //获取所有数据,设置推送
                CurrObjSys.GetValueEx(
                    mConn, mServerID, ID, 
                    GETSAMPLE_OBJ_INTERFACE.GET_PARAMS);
                CurrObjSys.GetValueEx(
                    mConn, mServerID, ID,
                    GETSAMPLE_OBJ_INTERFACE.GET_STATE);

                CurrObjSys.SenseConfigEx(
                    mConn, mServerID, ID,
                    0xffffffff, SENSE_CONFIG.ADD);

            }
        }
        public override void PushGetValue(IFConn from, uint srcid, ushort memid, byte[] infodata)
        {
            switch (memid)
            {
                case GETSAMPLE_OBJ_INTERFACE.GET_PARAMS:
                    {
                        string json = Misc.Converter.BytesToString(infodata);
                        var p = Newtonsoft.Json.JsonConvert.DeserializeObject<GETSAMPLE_OBJ_INTERFACE.Pack_Params>(json);


                        Enable = p.enable;
                        Range = p.range;
                        Velocity = p.velocity;
                        Window = p.window;
                        IsCheckByPercent = p.IsCheckByPercent;
                        ErrPercent = p.ErrPercent;
                        ErrValue = p.ErrValue;

                        for (int i = 0; i < Samples.Count() && i < p.samples.Count(); i++)
                        {
                            var sample_src = p.samples.ElementAt(i);
                            var sample_desp = Samples[i];

                            sample_desp.Enable = sample_src.enable;
                            sample_desp.JustForCheck = sample_src.justForCheck;
                            sample_desp.OrgAD = sample_src.orgad;
                            sample_desp.Position = sample_src.position;
                        }
                        Search = p.search;
                        for (int i = 0; i < Features.Count() && i < p.features.Count(); i++)
                        {
                            var feature_src = p.features.ElementAt(i);
                            var feature_desp = Features[i];


                            feature_desp.Enable = feature_src.enable;
                            feature_desp.StartPos = feature_src.startpos;
                            feature_desp.EndPos = feature_src.endpos;
                        }
                    } break;
                case GETSAMPLE_OBJ_INTERFACE.GET_STATE:
                    {
                        
                        string json = Misc.Converter.BytesToString(infodata);
                        var p = Newtonsoft.Json.JsonConvert.DeserializeObject<GETSAMPLE_OBJ_INTERFACE.Pack_State>(json);


                        PosOfGrid = p.posOfGrid;

                        for (int i = 0; i < Samples.Count() && i < p.samples.Count(); i++)
                        {
                            var sample_src = p.samples.ElementAt(i);
                            var sample_desp = Samples[i];

                            sample_desp.AD = sample_src.ad;
                            sample_desp.SampleValue = sample_src.value;
                        }
                        for (int i = 0; i < Features.Count() && i < p.features.Count(); i++)
                        {
                            var feature_src = p.features.ElementAt(i);
                            var feature_desp = Features[i];

                            feature_desp.MaxRelevancy = feature_src.maxRelevancy;
                            feature_desp.MaxOffset = feature_src.maxOffset;
                            feature_desp.ScanData = feature_src.scanData;
                        }
                    } break;
            }
        }
        public override void PushInfo(IFConn from, uint srcid, ushort infoid, byte[] infodata)
        {
            PushGetValue(from, srcid, infoid, infodata);
        }
        public override void PushCallFunction(IFConn from, uint srcid, uint magic, ushort funcid, byte[] retdata, object AsyncDelegate, object AsyncState)
        {
            switch (funcid) {
                case GETSAMPLE_OBJ_INTERFACE.CALL_GET_TEMPDATAS:
                    {
                        string json = Misc.Converter.BytesToString(retdata);

                        var reponse = Newtonsoft.Json.JsonConvert.DeserializeObject<List<List<TempFilterData>>>(json);
                        (AsyncDelegate as AsyncCBHandler)(AsyncState, reponse);
                    }
                    break;
            }
        }
        public void GetTempFilterDatas(AsyncCBHandler asyncCB, object asyncContext)
        {
            CurrObjSys.CallFunctionEx(mConn, mServerID, ID, GETSAMPLE_OBJ_INTERFACE.CALL_GET_TEMPDATAS, null, asyncCB, asyncContext);
        }
    }

}