using FLY.OBJComponents.IService;
using FLY.OBJComponents.Server;
using FLY.OBJComponents.Server.OBJProxy;
using FObjBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace FLY.DownBlowing.Server
{
    public class TDGage 
    {
        public string mParamDirectory;//参数目录 m_path;//数据文件的 根目录默认是 Gage1
        public string mName;//名字 如:gage0

        public SysParam mSysParam;
        public DownBlowingSystem mData;

        Model.DbModel mDbModel;
        public Model.HistoryDb mHistoryDb;
        public WarningSystem2 mWarning;
        public RotarySystem rotarySystem;
        public TDGage(string nam)
        {
            mName = nam;
            mParamDirectory = mName;// @"D:\" + m_name;

            if (!System.IO.Directory.Exists(mParamDirectory))
            {
                System.IO.Directory.CreateDirectory(mParamDirectory);
            }
            System.Environment.CurrentDirectory = mParamDirectory;

            mSysParam = new SysParam();
            mData = new DownBlowingSystem();

            mDbModel = new Model.DbModel();
            mHistoryDb = new Model.HistoryDb();
            mWarning = new WarningSystem2();
            rotarySystem = new RotarySystem();
        }
        #region Init登陆服务器初始化----------------------------------------------------
        /// <summary>
        /// 第1步, 加载本地数据
        /// </summary>
        public async Task Init()
        {
            //---------------------------------------------------------------------------------------------------------------
            //数据库
            await Task.Factory.StartNew(() =>
            {
                //初始数据库(加载 MaxId)
                mDbModel.Init();

                //删除不需要的备份数据
                mDbModel.KeepBackupSize(12);

                //备份上一个月之前的数据到 yyyy-MM 文件夹
                mDbModel.BackupBbInSize(12);

                //当前的数据库只保存上个月与这个月的数据
                mDbModel.KeepDBSize(1);
            });

            mHistoryDb.Init(mDbModel);

            
            mWarning.Init(mHistoryDb.ErrorBuffer);
            mData.Init(mHistoryDb, mWarning);

            rotarySystem.Init(mData.WinderAccessory);

            
            Misc.BindingOperations.SetBinding(
                mData.plcos.PLCs[0].Client, nameof(Modbus.WithThread.ClientTCP.IsConnected), () => {
                if (mData.plcos.PLCs[0].Client.IsConnected)
                    rotarySystem.StartMeasureRPos();
                else
                    rotarySystem.StopMeasureRPos();
            });
        }
        


        #endregion

    }
}