using Insight.Agent.Extensions;
using Insight.Agent.Interfaces;
using Insight.Agent.Messages;
using Insight.Agent.Network;
using Insight.Agent.Network.Handlers;
using Insight.Agent.Services;
using Insight.Domain.Constants;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Vaitr.Network;

namespace Insight.Agent.Windows
{
    internal class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = Host.CreateDefaultBuilder(args);
            builder.UseWindowsService();
            builder.UseSystemd();

            builder.ConfigureAppConfiguration(config =>
            {
                config.Defaults();
            });

            builder.ConfigureLogging(options =>
            {
                options.ClearProviders();
                options.SetMinimumLevel(LogLevel.Trace);

                options.AddSimpleConsole(options =>
                {
                    options.IncludeScopes = true;
                    options.SingleLine = true;
                    options.TimestampFormat = "yyyy-MM-dd HH:mm:ss.fff ";
                });

                options.AddFile($"{Configuration.AppDirectory?.FullName}/" + "logs/agent_{Date}.log", LogLevel.Trace, fileSizeLimitBytes: 104857600, retainedFileCountLimit: 10, outputTemplate: "{Timestamp:o} [{Level:u3}] {Message} {NewLine}{Exception}");
            });

            builder.ConfigureServices((host, services) =>
            {
                // SERVICES
                services.AddHostedService<UpdateService>();
                services.AddHostedService<TrapService>();

                // SERVICES (WINDOWS)
                if (OperatingSystem.IsWindows()) services.AddHostedService<EventService>();

                // AGENT NETWORKING
                services.UseHostedTcpClient<AgentSession, MemPackSerializer, IAgentMessage>(options =>
                {
                    options.Host = host.Configuration.GetValue<string?>(Appsettings.ServerHost) ?? throw new Exception($"{Appsettings.ServerHost} value not set (appsettings)");
                    options.Port = host.Configuration.GetValue<int?>(Appsettings.ServerPort) ?? throw new Exception($"{Appsettings.ServerPort} value not set (appsettings)");
                    options.Buffer = 1024 * 1024;
                    options.KeepAlive = 10000;
                    options.Timeout = 30000;
                    options.Parallelism = 0;
                    options.Compression = Compression.None;
                    options.Encryption = Encryption.Tls12;
                    options.SslPolicy = SslPolicy.None;

                    //options.InputRateLimit = 1024 * 1024 * 100;
                    //options.OutputRateLimit = 1024 * 1024 * 100;
                });

                services.AddSingleton<IAgentMessageHandler<AgentSession>, AuthenticationHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, DriveHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, InterfaceHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, MainboardHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, MemoryHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, OperationSystemHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, PrinterHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, ProcessorHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, ServiceHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, SessionHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, SoftwareHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, StoragePoolHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, SystemInfoHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, UpdateHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, UserHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, VideocardHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, VirtualMaschineHandler>();
                services.AddSingleton<IAgentMessageHandler<AgentSession>, ConsoleHandler>();

                // GLOBAL DEPENDENCIES
                services.AddTransient(provider => new HttpClient(new HttpClientHandler
                {
                    ClientCertificateOptions = ClientCertificateOption.Manual,
                    ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => true
                }));
            });

            var host = builder.Build();
            await host.RunAsync().ConfigureAwait(false);
        }
    }
}