using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using Wayne.FDCPOSLibrary;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using System.Net.Http;
using System.Net.Http.Headers;
using Edge.Core.Processor;
using Edge.Core;
using Edge.Core.UniversalApi;
using Edge.Core.Processor.Dispatcher.Attributes;
using Edge.Core.IndustryStandardInterface.Pump;
using Edge.Core.Processor.Dispatcher;

namespace Application.LicensingApp
{
    [MetaPartsDescriptor(
        "lang-zh-cn:验证码lang-en-us:LicensingApp",
        "lang-zh-cn:用于验证设备是否有权限访问服务lang-en-us:Used to check if the device has right to access the services",
        new[] { "lang-zh-cn:验证码lang-en-us:LicensingApp" })]
    public class App : IAppProcessor
    {
        public IServiceProvider Services { get; }
        public string MetaConfigName { get; set; }
        public string SerialNumber { get; set; }
        public ILogger Logger { get; } = NullLogger.Instance;
        private IEnumerable<IProcessor> _processors;

        public App(IServiceProvider services, int id)
        {
            this.Services = services;
            if (services != null)
            {
                var loggerFactory = services.GetRequiredService<ILoggerFactory>();
                Logger = loggerFactory.CreateLogger("Application");
            }
        }

        public void Init(IEnumerable<IProcessor> processors)
        {
            _processors = processors;
        }

        public Task<bool> Start()
        {
            if (CheckLicense().Result == false)
            {
                var macAddress = Licensing.Instance().GetMacAddress(Logger);
                LogInfo($"License not found! Please enter license code from web page, physical address {macAddress}");
                Task.Delay(15 * 1000).ContinueWith(_ =>
                {
                    _processors?.OfType<DefaultDispatcher>().First()
                        .StopProcessorsAsync(
                            _processors.WithHandlerOrApp<IFdcPumpController>().Concat(
                                _processors.WithHandlerOrApp<IEnumerable<IFdcPumpController>>()), "Licensing check failed");
                });
            }
            else
            {
                LogInfo(@"License OK!");
            }

            return Task.FromResult(true);
        }

        [UniversalApi]
        public async Task<bool> CheckLicense(string license = "")
        {
            return await Licensing.Instance().CheckLicense();
        }

        [UniversalApi]
        public async Task<bool> VerifyLicense(string license)
        {
            var result = await Licensing.Instance().VerifyLicense(license);
            if (result == true)
            {
                LogInfo("License verification OK, please restart LiteFccCore to apply the license.");
            }
            else
            {
                LogInfo("License verification failed, please try again.");
            }
            return result;
        }

        public Task<bool> Stop()
        {
            return Task.FromResult(true);
        }

        private void LogInfo(string msg)
        {
            Console.WriteLine("       " + msg);
            Logger.LogError(msg);
        }
    }
}