using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Threading;
using Newtonsoft.Json;
using NLog;
using NLog.Config;
using ProfitGroup.Rdnl.Extensions;
using ProfitGroup.SampleService.Models;
using RnD.API;
using System.Management.Instrumentation;

namespace ProfitGroup.SampleService.Core.Services
{
    public class QueueHandler
    {
        private ILogger Logger
        {
            get
            {
                var loggerConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nlog.config");
                LogManager.Setup().LoadConfigurationFromFile(loggerConfig);
                LogManager.Configuration = new XmlLoggingConfiguration(loggerConfig);

                return LogManager.GetCurrentClassLogger();
            }
        }

        private readonly ConcurrentQueue<MT_InspLot> _queue;
        private readonly CancellationTokenSource _cancellationTokenSource;
        private readonly RDnLManager _manager;
        private readonly KsssInfoService _ksssInfoService;
        private readonly SampleService _sampleService;
        private readonly API _api;
        private readonly Appsettings _appSettings;

        public QueueHandler(RDnLManager manager,
            ConcurrentQueue<MT_InspLot> queue,
            API api)
        {
            _queue = queue;
            _cancellationTokenSource = new CancellationTokenSource();


            var loggerConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nlog.config");
            LogManager.Setup().LoadConfigurationFromFile(loggerConfig);
            LogManager.Configuration = new XmlLoggingConfiguration(loggerConfig);

            _manager = manager;
            _queue = queue;
            _ksssInfoService = new KsssInfoService(manager, api);
            _sampleService = new Core.Services.SampleService(manager, api, new SampleConfirmationService(manager, api));
            _api = api;

            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
            _appSettings = JsonConvert.DeserializeObject<Appsettings>(File.ReadAllText(path));
        }

        public void StartProcessing()
        {
            Task.Run(async () =>
            {
                while (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    MT_InspLot item;
                    while (_queue.TryDequeue(out item))
                    {
                        await Process(item);
                    }

                    Underload();
                }
            }, _cancellationTokenSource.Token);
        }

        public void StopProcessing()
        {
            _cancellationTokenSource.Cancel();
        }

        private async Task Process(MT_InspLot request)
        {
            
        }

        private void Underload()
        {
            Thread.Sleep(1000);
        }

        #region Приватные методы

        private void PushLogSeparator(int newLineCount = 0)
        {
            Logger.Info($"{new string('=', 100)}{new string('\n', newLineCount)}");
        }

        private object GetPropertyValue(object objectDocument, string propertyName)
        {
            Type type = objectDocument.GetType();
            PropertyInfo propertyInfo = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);

            if (propertyInfo != null)
                return propertyInfo.GetValue(objectDocument, null);
            else
                return null;
        }

        #endregion
    }
}