using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using HTCoreServiceApp.Common;
using HTCoreServiceApp.DriverInterface;
using HTCoreServiceApp.Models;
using Microsoft.Extensions.Logging;
using HTCoreServiceApp.Communicate;
using System.Text.RegularExpressions;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics.CodeAnalysis;
using SqlSugar;

namespace HTCoreServiceApp
{
    public class DriverThread : IDisposable
    {
        public readonly List<MetaSystem> MetaSystem;
        public readonly MetaDriver MetaDriver;
        public readonly List<MetaGroup> metaGroups;
        public readonly List<MetaTag> metaTagColls;
        public readonly string driverName;
        public IDriverEntity DriverEntity;
        private readonly ILogger logger;
        private Task? _task;
        private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
        private readonly object _lock = new();
		public DriverThread(MetaDriver metaDriver) 
        {

            MetaDriver= metaDriver;
			//string ConnectionStrings = AESKeyEncrypt.DecryptDES(ConfigHelper.ReadAppSettings("ConnectionStrings", "SqlServer"));
			var db = new SqlSugarClient(StaticLibrary.DBConfig);
			var argument =db.Queryable<MetaArgument>().Where(x => x.DriverId == MetaDriver.DriverId).ToList(); //db.Arguments.Where(x => x.DriverId == MetaDriver.DriverId).ToList(); ;
			if (argument.Count <1)
            {
                Console.WriteLine($"找不到该设备参数:{MetaDriver.DriverName}");
                LogHelper.LogWrite($"找不到该设备参数:{MetaDriver.DriverName}");
                return;
            }

            metaGroups = db.Queryable<MetaGroup>().Where(x => x.DriverId == metaDriver.DriverId).ToList();// db.MetaGroups.Where(x => x.DriverId == metaDriver.DriverId).ToList() ;


            metaTagColls = db.Queryable<MetaTag>().ToList(); //db.MetaTags.ToList();
            var groupMetaTags = EFLinqExtenHelper.GetGroupMetaTags(metaTagColls, metaGroups.Select(x => x.GroupId).ToArray());
            driverName = db.Queryable<MetaDriver>().Where(x => x.DriverId == MetaDriver.DriverId).First().DriverName; //db.MetaDrivers.Where(x => x.DriverId == MetaDriver.DriverId).First().DriverName;

            MetaSystem = db.Queryable<MetaSystem>().ToList();

			TagGroup tagGroup = new TagGroup() {
                
                Tags = groupMetaTags,
                Arguments = argument,
                Groups = metaGroups,
                DriverName= driverName,
                Systems  = MetaSystem
            };

			//var groups = metaGroups.GroupBy(x => new { x.GroupId });
			//foreach (var metaGroup in groups)
			//{
			//    //if 添加连续或单变量读取标记
			//    tagGroup.SplitTags.Add(metaTags.Where(x => x.GroupId == metaGroup.Key.GroupId).ToList());
			//}
			//DriverEntity = CommunicationAdapter.GetAdapter(tagGroup);
			Task.Run(() =>
            {
                DriverEntity = CommunicationAdapter.GetAdapter(tagGroup);
            });
            //DriverEntity = CommunicationAdapter.GetAdapter(argument, metaGroups, metaTags);

            //DriverEntity = new DriverEntity()
            //{
            //    DeviceId = argument[0].DriverId.ToString(),
            //    IsConnected = false,
            //    Timeout = int.Parse(argument[3])
            //};
            //logger.LogInformation($"线程已启动:{MetaDriver.DriverName}");
            Thread.Sleep(1000);
            _task = Task.Run(() =>
            {
                while (true)
                {
                    if (_tokenSource.IsCancellationRequested)
                    {
                        //logger.LogInformation($"停止线程:{MetaDriver.DriverName}");
                        return;
                    }
                    lock (_lock)
                    {
                        try
                        {
                            if (DriverEntity.IsConnected)
                            {

                            }
                            else
                            {
                                
                            }
                        }
                        catch(Exception ex) 
                        {

                        }
                    }
                    Thread.Sleep(1000);
                }
            });

            
        }

        public int DriverWrite(WritePara para)
		{
			return DriverEntity.Write(para);
		}
        public int DriverBlockWrite(WriteBlockPara para)
        {
            return DriverEntity.WriteBlock(para);
        }

        public void StopThread()
        {

        }
        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}
