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

using Misc;
using FlyADBase;
using FLY.Thick.BulkDataModule;
using FLY.Thick.Base.Common;
using FLY.Thick.Base.IService;
namespace FLY.Thick.Base.Server
{


    public class GM_Scan : GM_ScanMotion
    {
        protected IBoltMapBase mBoltmap;
        protected BorderSearch mBorderSearch;
        protected IBulkDataServiceAdd mBulkData;
        protected DynArea mDynArea;
        protected AD2ThickHandler AD2Thick;
        /// <summary>
        /// 剔除数据用
        /// </summary>
        protected Reject mReject;

        public int m_scanCnt;//扫描次数
        public DIRECTION m_scanDir;//扫描方向
        public int[] m_boltmap_thick;//分区后thick
        private bool bTemp = false;//bulkdata 最新的一幅数据是临时数据，需要清空
        public GM_Scan(FlyAD7 flyad, GSample gsample)
            : base(flyad, gsample)
        {
            ScanCnt = -1;
            //接收PollScan的推送
            DataPosEvent += new EndEventHandler(pollScan_DataPosEvent);
            EndEvent += new EndEventHandler(pollScan_EndEvent);
        }

        public void Init(
            Reject reject, 
            IBoltMapBase boltmap,BorderSearch bordersearch,
            IBulkDataServiceAdd bulkdata, DynArea dynarea, AD2ThickHandler func_ad2thick)
        {

            mReject = reject;
            mBoltmap = boltmap;
            mBorderSearch = bordersearch;

            mBulkData = bulkdata;
            mDynArea = dynarea;

            AD2Thick = func_ad2thick;

            Misc.BindingOperations.SetBinding(mFlyAD, "PosLen", mReject, "PosLen");
            Misc.BindingOperations.SetBinding(mFlyAD, "PosOfGrid", mReject, "PosOfGrid");
        }

        protected virtual void pollScan_EndEvent(object obj, FlyADBase.MiniGridEventArgs e)
        {
            DIRECTION direction = e.direction;

            int posOfGrid = e.posOfGrid;
            int start_grid = e.grid_start;
            int start_pos = e.grid_start * e.posOfGrid;

            int[] dat = e.buf;
            
            mBoltmap.InitBoltAD();

            if (gsample.Enable)
            {
                if(!gsample.OK())
                {
                    mBulkData.ChangeEmply();
                    return;//样品还没获取成功
                }
            }

            //找边界
            if (mBorderSearch.Enable)
            {
                bool ret = mBorderSearch.FindFilm(direction, posOfGrid, start_grid, dat);
                if (!ret)//不能找到边界!
                {
                    mBorderSearch.Init();
                    mBoltmap.InitExChange();
                }
                //设置扫描范围
                //POLLSCAN----------------------------------------	
                int beginPos;
                int endPos;
                mBorderSearch.GetScanRange(out beginPos, out endPos);

                ScanStart = beginPos;
                ScanEnd = endPos;

                //mBorderSearch.GetBoltRange(direction, out beginPos, out endPos);

                Range border = mBorderSearch.GetBorder(direction);
                //mBoltmap
                mBoltmap.CalExChange(direction, border);
            }




            //----------------------------------------------------
            //FRAME
            int len = dat.Length;
            int[] _temp_thicks = new int[len];//减少数据量, 降低噪声，避免剔除时，把噪声剔除。剔除的目前只是为了剔走基材，不是为了滤波


            //AD值转厚度值
            for (int i = 0; i < len; i++)
            {
                _temp_thicks[i] = AD2Thick(dat[i]);
            }

            //只有当数据有效时，也就是膜在跑时，才会剔除数据。 默认 pDyn->m_dataValid=TRUE; 
            //只有在接到推送时，才会有可能变为pDyn->m_dataValid=FALSE;
            //这样的目前是,方便设置平移补偿！！

            mReject.DoFrameFilter(mDynArea.Target, start_grid, _temp_thicks);


            m_boltmap_thick = mBoltmap.Map(direction, start_pos, posOfGrid, _temp_thicks);
            //把左右数据删除
            for (int i = 0; i < m_boltmap_thick.Count(); i++) 
            {
                if((i < (mDynArea.DataBoltNoBegin - mDynArea.FirstBoltNo))||(i > (mDynArea.DataBoltNoEnd - mDynArea.FirstBoltNo)))
                {
                    m_boltmap_thick[i] = Misc.MyBase.NULL_VALUE;
                }
            }

            m_scanCnt++;//扫描次数
            m_scanDir = direction;//扫描方向

            //----------------------------------------------------
            //数据库
            FR_DATA_TYPE t = FR_DATA_TYPE.INVALID;
            if (mDynArea.DataValid)
                t = FR_DATA_TYPE.VALID;
            mBulkData.Change(0, 0, m_boltmap_thick, t);

            mBulkData.Save();

            //添加一幅空数据

            mBulkData.AddEmply();
        }

        void pollScan_DataPosEvent(object obj, FlyADBase.MiniGridEventArgs e)
        {
            
            Misc.DIRECTION direction = e.direction;

            int posOfGrid = e.posOfGrid;
            int start_grid = e.grid_start;
            int start_pos = e.grid_start * e.posOfGrid;

            //TODO
            int[] data = e.buf.Clone() as int[];
            //-------------------------------------
            //DIR
            mDynArea.Direction = direction;
            mDynArea.AD = data[0];

            //2.转为thick
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = AD2Thick(data[i]);
            }


            //3.动态分区

            int start_boltIndex;
            int[] boltThick;

            if (mBoltmap.UpdateBoltAD(data, start_pos, posOfGrid, direction, out start_boltIndex, out boltThick))
            {
                mDynArea.Thick = boltThick[0];
                //----------------------------------------------------
                //数据库
                FR_DATA_TYPE t = FR_DATA_TYPE.INVALID;
                if (mDynArea.DataValid)
                    t = FR_DATA_TYPE.VALID;

                if (!mBulkData.Change(0, start_boltIndex, boltThick, t))
                {
                    mBulkData.AddEmply();
                    mBulkData.Change(0, start_boltIndex, boltThick, t);
                }
                bTemp = true;
            }
        }

        public override bool Start()
        {
            bool b = base.Start();
            if (!b)
                return false;

            //设置扫描范围
            int beginPos = 0, endPos = mFlyAD.PosLen - 1;
            if (mBorderSearch.Enable)
            {
                mBorderSearch.Init();
                mBorderSearch.GetScanRange(out beginPos, out endPos);
            }
            else
            {
                mBoltmap.GetScanRange(
                    new Range() { Begin = mDynArea.ScanBoltNoBegin, End = mDynArea.ScanBoltNoEnd },
                    out beginPos, out endPos);
            }
            if (beginPos < 0)
                beginPos = 0;

            if (endPos > mFlyAD.PosLen)
                endPos = mFlyAD.PosLen;

            mBoltmap.InitBoltAD();
            //初始化推送
            mBulkData.InitPush();

            if (bTemp)
            {
                //之前有一幅临时数据剩下来
                if (!mBulkData.ChangeEmply())
                    mBulkData.AddEmply();
            }
            else
            {
                //添加空的数据
                mBulkData.AddEmply();
            }
             bTemp = false;
            return base.Start2(beginPos, endPos);
        }
        public override void Stop()
        {
            base.Stop();
        }
    }
}
