using System.IO;
using System.Windows;
using System.Windows.Input;
using NexusInstaller.Models;
using NexusInstaller.Services;
using NexusInstaller.ViewModels;

namespace NexusInstaller.Views;

public partial class NexusSetupWindow : Window
{
    private readonly NexusSetupViewModel _viewModel;
    private readonly string? _captureScreenshotsDir;

    public NexusSetupWindow(InstallerOptions options)
    {
        InitializeComponent();
        _viewModel = new NexusSetupViewModel(options);
        DataContext = _viewModel;
        _captureScreenshotsDir = options.CaptureScreenshotsDir;

        if (!string.IsNullOrWhiteSpace(_captureScreenshotsDir))
        {
            Loaded += OnEvidenceCaptureLoaded;
        }
    }

    private async void OnEvidenceCaptureLoaded(object sender, RoutedEventArgs e)
    {
        Loaded -= OnEvidenceCaptureLoaded;

        if (string.IsNullOrWhiteSpace(_captureScreenshotsDir))
        {
            return;
        }

        try
        {
            var dir = Path.GetFullPath(_captureScreenshotsDir);
            var captures = new (string FileName, Func<Task> Prepare)[]
            {
                ("installer-welcome.png", () => _viewModel.PrepareEvidenceStepAsync(InstallerStep.Welcome)),
                ("installer-requirements.png", () => _viewModel.PrepareEvidenceStepAsync(InstallerStep.Requirements)),
                ("installer-identity.png", () => _viewModel.PrepareEvidenceStepAsync(InstallerStep.Identity)),
                ("installer-installing.png", async () =>
                {
                    await _viewModel.PrepareEvidenceStepAsync(InstallerStep.Install);
                    _viewModel.PrepareEvidenceInstalling();
                }),
                ("installer-complete.png", async () =>
                {
                    await _viewModel.PrepareEvidenceStepAsync(InstallerStep.Install);
                    _viewModel.PrepareEvidenceComplete();
                }),
            };

            foreach (var (fileName, prepare) in captures)
            {
                await prepare();
                await EvidenceScreenshotService.CaptureAsync(this, Path.Combine(dir, fileName));
            }
        }
        finally
        {
            Close();
            Application.Current.Shutdown(0);
        }
    }

    private void CloseButton_Click(object sender, RoutedEventArgs e) => Close();

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Escape)
        {
            Close();
        }
    }
}
