using Insight.Remote.Shared.Abstractions;
using Insight.Remote.Shared.Messages;
using Insight.Remote.Shared.Native.Windows;
using Insight.Remote.Shared.Reactive;
using Insight.Remote.Shared.Services;
using Microsoft.Extensions.Logging;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Security.Principal;
using Vaitr.Bus;

namespace Insight.Remote.Windows.ViewModels;

public class MainViewModel : ViewModelBase
{
    public string StatusMessage
    {
        get => Get<string>() ?? string.Empty;
        set => Set(value);
    }

    public bool IsAdministrator { get; } = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
    public bool CanElevateToAdmin => !IsAdministrator;
    public bool CanElevateToService => IsAdministrator && !WindowsIdentity.GetCurrent().IsSystem;

    public RelayCommand ElevateToAdminCommand { get; }
    public RelayCommand ElevateToServiceCommand { get; }

    private string? _lastId;

    private readonly List<IDisposable> _subscriptions = new();

    private readonly Bus _bus;
    private readonly IDispatcher _dispatcher;
    private readonly ILogger<MainViewModel> _logger;

    public MainViewModel(Bus bus, IDispatcher dispatcher, ILogger<MainViewModel> logger)
    {
        _bus = bus;
        _dispatcher = dispatcher;
        _logger = logger;

        ElevateToAdminCommand = new RelayCommand(ElevateToAdmin, () => CanElevateToAdmin);
        ElevateToServiceCommand = new RelayCommand(ElevateToService, () => CanElevateToService);

        _subscriptions.Add(_bus.SubscribeAsync<ConnectionStateChanged>(OnConnectionStateChangedAsync, null));
        _subscriptions.Add(_bus.SubscribeAsync<IdentityChanged>(OnIdentityChangedAsync, null));
    }

    private async ValueTask OnConnectionStateChangedAsync(ConnectionStateChanged message, CancellationToken cancellationToken)
    {
        switch (message.State)
        {
            case ConnectionState.Connecting:
                {
                    await _dispatcher.InvokeAsync(() => StatusMessage = "Connecting...", cancellationToken);
                    break;
                }
            case ConnectionState.Reconnecting:
                {
                    await _dispatcher.InvokeAsync(() => StatusMessage = "Reconnecting...", cancellationToken);
                    break;
                }
            case ConnectionState.Connected:
                {
                    await _dispatcher.InvokeAsync(() => StatusMessage = "Connected", cancellationToken);
                    break;
                }
            case ConnectionState.Disconnected:
                {
                    await _dispatcher.InvokeAsync(() => StatusMessage = "Disconnected", cancellationToken);
                    break;
                }
            case ConnectionState.Error:
                {
                    await _dispatcher.InvokeAsync(() => StatusMessage = "Error", cancellationToken);
                    break;
                }
        }
    }

    private async ValueTask OnIdentityChangedAsync(IdentityChanged message, CancellationToken cancellationToken)
    {
        var format = "";
        for (var i = 0; i < message.Id.Length; i += 3) format += $"{message.Id.Substring(i, 3)} ";

        _lastId = format.Trim();

        if (_lastId is not null) await _dispatcher.InvokeAsync(() => StatusMessage = _lastId, cancellationToken);
    }

    public void Shutdown()
    {
        _dispatcher.ShutdownAsync();
    }

    private void ElevateToAdmin()
    {
        try
        {
            var commandLine = Win32Interop.GetCommandLine().Replace(" --elevate", "");
            var sections = commandLine.Split('"', StringSplitOptions.RemoveEmptyEntries);
            var filePath = sections.First();
            var arguments = string.Join('"', sections.Skip(1));
            var psi = new ProcessStartInfo(filePath, arguments)
            {
                Verb = "RunAs",
                UseShellExecute = true,
                WindowStyle = ProcessWindowStyle.Hidden
            };
            Process.Start(psi);
            Environment.Exit(0);
        }
        // Exception can be thrown if UAC is dialog is cancelled.
        catch { }
    }

    private void ElevateToService()
    {
        try
        {
            var psi = new ProcessStartInfo("cmd.exe")
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = true
            };

            var commandLine = Win32Interop.GetCommandLine().Replace(" --elevate", "");
            var sections = commandLine.Split('"', StringSplitOptions.RemoveEmptyEntries);
            var filePath = sections.First();
            var arguments = string.Join('"', sections.Skip(1));

            _logger.LogInformation("Creating temporary service with file path {filePath} and arguments {arguments}.",
                filePath,
                arguments);

            psi.Arguments = $"/c sc create RemoteControl_Temp binPath=\"{filePath} {arguments} --elevate\"";
            Process.Start(psi)?.WaitForExit();
            psi.Arguments = "/c sc start RemoteControl_Temp";
            Process.Start(psi)?.WaitForExit();
            psi.Arguments = "/c sc delete RemoteControl_Temp";
            Process.Start(psi)?.WaitForExit();

            _dispatcher.ShutdownAsync();
        }
        catch { }
    }
}

public class FakeMainViewModel : ViewModelBase
{
    public RelayCommand ElevateToAdminCommand { get; } = new(() => { });
    public RelayCommand ElevateToServiceCommand { get; } = new(() => { });

    public bool IsAdministrator => false;
    public string StatusMessage { get; set; } = "test";
}