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

using System.ComponentModel;

using FLY.Thick.Base.Common;
using FLY.Thick.Base.IService;
using Misc;
using FlyADBase;
using FObjBase;

namespace FLY.Thick.Base.Server
{
    public class GM_Fix : IGageMode, IFixService
    {
        #region IGageMode
        public CTRL_STATE GMState
        {
            get { return CTRL_STATE.FIX; }
        }

        public bool IsRunning { get; protected set; }

        #endregion

        #region IFixService
        public DateTime UpdateTime { get; private set; }
        #endregion

        /// <summary>
        /// 闲置时（IsRunning==false） 忽略数据
        /// </summary>
        public bool IsIgnoreDataWhenIdle { get; set; } = true;
        FlyADBase.FlyAD7 mFlyAD;
        DynArea mDynArea;
        AD2ThkHandler Ad2Thk;
        GetFixDatasReponse reponse;
        public GM_Fix() 
        {
            
            
        }
        public void Init(FlyADBase.FlyAD7 flyad, DynArea dynarea, AD2ThkHandler func_ad2thk)
        {
            mFlyAD = flyad;

            mDynArea = dynarea;

            Ad2Thk = func_ad2thk;

            flyad.TimeGridEvent += new FlyADBase.TimeGridEventHandler(flyad_TimeGridEvent);
        }
        /// <summary>
        /// 1s 的AD值，就只是用来显示到主界面左上面角而已 DynArea.AD
        /// </summary>
        List<int> Data1s = new List<int>();
        

        void flyad_TimeGridEvent(object sender, FlyADBase.TimeGridEventArgs e)
        {
            DateTime dt = e.Time;
            TimeSpan ts = e.Ts;
            var datas = e.Data.ToArray();

            //1秒数据, 大概而已
            Data1s.AddRange(datas);
            if (TimeSpan.FromTicks(Data1s.Count * ts.Ticks) >= TimeSpan.FromSeconds(1)) 
            {
                int ad = (int)Data1s.Average();
                Data1s.Clear();

                mDynArea.AD = ad;
                mDynArea.Thk = Ad2Thk(ad);
            }


            //转换为thick
            double[] thks = datas.Select((ad) => Ad2Thk(ad)).ToArray();

            reponse = new GetFixDatasReponse()
            {
                ADs = datas,
                thicks = thks,
                time = dt,
                ts = ts
            };

            UpdateTime = dt;
        }

        #region IGageMode
        public void Start()
        {
            IsRunning = true;
        }

        public void Stop()
        {
            IsRunning = false;
        }

        #endregion


        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        public void GetFixDatas(AsyncCBHandler asyncDelegate, object asyncContext)
        {
            asyncDelegate(asyncContext, reponse);
        }
    }
}
