using CatLib;
using Highway.Assemble.common;
using Mesnac.DeviceAdapterNet;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;

namespace HighWayAssemble
{
    public class FrmDisplayControl
    {
        FrmDisplayView view;
        ISoftInfo m_softInfo;
        /// <summary>
        /// 注册视图层插件
        /// </summary>
        /// <param name="view"></param>
        public FrmDisplayControl(FrmDisplayView view)
        {
            this.view = view;
            OnRegister();//绑定
            /* m_model =*/
            new FrmDisplayModel();
            // m_ConfigInfo = App.Make<IConfigInfo>();
            m_softInfo = App.Make<ISoftInfo>();

        }
        /// <summary>
        /// 初始化加载系统
        /// </summary>
        public void StartLoad()
        {
            App.TriggerHalt(EventSystem.StartLoad);
        }
        /// <summary>
        /// 加载视图窗体
        /// </summary>
        public void LoadCollectID()
        {
            view.Hide();
            System.Threading.Thread.Sleep(200);
            using (SetCollectIDView form = new SetCollectIDView())
            {
                form.ShowDialog();
            }
            System.Threading.Thread.Sleep(200);
            view.Show();
        }
        #region 更新
        bool isNeedUpdate = false;
        int delayTime = 1000 * 60 * 10;
        /// <summary>
        /// 获取版本信息
        /// </summary>
        public void GetVersionInfo()
        {
            var localVersion = FileToString(System.Environment.CurrentDirectory + "\\Version.txt");
            view.SetVersionInfo(localVersion);

            var t = Task.Run(async delegate
            {
                while (true)
                {
                    if (!isNeedUpdate)
                    {
                        var Version = GetVersion();

                        if (!string.IsNullOrEmpty(Version) && Version != localVersion)
                        {
                            isNeedUpdate = true;
                            delayTime = 1000;
                        }
                    }
                    else
                    {
                        view.SetVersionInfo("有新的更新！", true);
                    }
                    await Task.Delay(delayTime);
                }

            });
        }
        /// <summary>
        /// 获取服务器上汇集软件的版本信息
        /// </summary>
        /// <returns>服务器上汇集软件版本信息</returns>
        string GetVersion()
        {
            try
            {
                var request = WebRequest.Create(m_softInfo.CollectInfo.UpdateUrl + "/Version.txt");
                var response = request.GetResponse();
                using (var stream = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    var content = stream.ReadToEnd();//获取到远程的页面字符串

                    return content;// Console.WriteLine(content);
                }
            }
            catch (Exception)
            {
                //  view.ShowMessageBox("网络连接失败，请检查网络", "警告", null, 16);
                return null;
            }
        }
        /// <summary>
        /// 获取文件中的数据
        /// </summary>
        /// <param name="filePath">文件路径</param>
        public string FileToString(String filePath)
        {
            string strData = "";
            try
            {
                string line;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        strData = line;
                    }
                }
            }
            catch (Exception e)
            {
                //  MessageBox.Show(string.Format("读取{0}文件失败", filePath), "提示");
            }
            return strData;
        }
        #endregion
        /// <summary>
        /// 窗体关闭停用插件
        /// </summary>
        public void AppClosed()
        {
            App.TriggerHalt(EventSystem.AppClosed);
            App.Off(EventSystem.UpdateViewList);
            App.Off(EventSystem.UpdateMesListInfo);
            App.Off(EventSystem.updateEquipListInfo);
            App.Off(EventSystem.updateSensorListInfo);
            App.Off(EventSystem.MessageBox);
            // App.Off(EventSystem.SetFromName);
            App.Off(EventSystem.LoadCollectID);
        }
        /// <summary>
        /// 注册插件
        /// </summary>
        void OnRegister()
        {
            App.On(EventSystem.UpdateViewList, (ISoftInfo softInfo) =>
            {
                view.UpdateMesListView(softInfo.mesSoftList);
                view.FreshEquipListView(softInfo.EquipList);
                view.FreshSensorListView(softInfo.SensorList);

                view.SetCollectID(softInfo.CollectInfo.collectID, softInfo.CollectInfo.collectName);
                view.SetFromName(softInfo.CollectInfo.collectName);
            });
            App.On(EventSystem.UpdateMesListInfo, (List<mesSoft> mesinfo) =>
            {
                view.UpdateMesListView(mesinfo);
            });
            App.On(EventSystem.updateEquipListInfo, (List<DeviceInfo> state) =>
            {
                for (int i = 0; i < state.Count; i++)
                {
                    view.equipState(state[i].m_iDeviceId.ToString(), state[i].m_ConnectState);
                }
            });
            //更新传感器读取数据
            App.On(EventSystem.updateSensorListInfo, (string id, string data) =>
            {
                view.DealData(id, data);
            });
            App.On(EventSystem.MessageBox, (string info, string caption, int icon) =>
            {
                view.ShowMessageBox(info, caption, null, icon);
            });
            //App.On(EventSystem.SetFromName, (string fromname,string CollectID) => {
            //    view.SetCollectID(CollectID);
            //    view.SetFromName(fromname);
            //});
            App.On(EventSystem.LoadCollectID, LoadCollectID);
        }
    }
}
