using System;
using System.Configuration;
using NewLife.Data;
using NewLife.Serialization;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using NewLife.Log;
using OPC_Client;
using Pas.ScadaService.Core;
using System.Web.UI.WebControls;

namespace Pas.ScadaService
{
    public class StartUp
    {
        private static Core.ScadaService _scada;
        private static bool _isStart;
        public static void Start()
        {
            var serverName = ConfigurationManager.AppSettings["ServerName"];
            var pointFile = ConfigurationManager.AppSettings["PointFile"];
            var config = ConfigurationManager.AppSettings["ConfigFile"];
            var sqlConn = ConfigurationManager.AppSettings["SqlConn"];
            _scada = new Core.ScadaService(serverName, pointFile);
            _scada.ChangeEvent += (data, changeItems) =>
            {
                if (!_isStart) return;
                var dataList =
                    data.Where(c => changeItems.Contains(c.Key))
                        .Select(c => new Model.Data
                        {
                            BatchNum = c.Value.batchNum,
                            DataType = c.Value.dataType,
                            DateTime1 = c.Value.DateTime1.ToString("yyyy-MM-dd HH:mm:ss"),
                            Id = c.Value.id,
                            ItemId = c.Value.itemID,
                            TimeStamp = c.Value.timeStamp,
                            Value = c.Value.value
                        })
                        .ToList();
                try
                {
                    GopTimeCalc.ChangeData(dataList);
                }
                catch (Exception e)
                {
                    XTrace.Log.Error(e.ToString());
                }

            };
            _scada.Start();
            Thread.Sleep(3000);
            GopTimeCalc.Load(config, sqlConn, GetAllData());
            _isStart = true;
        }
        private static List<Model.Data> GetAllData()
        {
            return _scada.GetAllData().Select(c => new Model.Data
            {
                BatchNum = c.batchNum,
                DataType = c.dataType,
                DateTime1 = c.DateTime1.ToString("yyyy-MM-dd HH:mm:ss"),
                Id = c.id,
                ItemId = c.itemID,
                TimeStamp = c.timeStamp,
                Value = c.value
            }).ToList();
        }
    }
}