using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using LindtLeerformPlugin.ViewModels;
using LindtLeerformPlugin.Views;
using Serilog;
using VisionBuilder.UI.Common;
using VisionBuilder.UI.Common.Processing;
using VisionBuilder.UI.Common.ViewModel.Classes;

namespace LindtLeerformPlugin;

public class LeerformModule : IVisionBuilderModule
{
    private readonly SingleCameraVM _singleCameraVm;
    private readonly LeerformSettings _settings;
    private readonly IImageSource _imageSource;

    public LeerformModule(SingleCameraVM singleCameraVm, LeerformSettings settings, IImageSource imageSource)
    {
        _singleCameraVm = singleCameraVm;
        _settings = settings;
        _imageSource = imageSource;
    }

    public void InitializeModule()
    {
        var calibrateButton = new ButtonDefinition("leerform_calibrate", "Calibrate", OnCalibrateClicked);
        _singleCameraVm.AddButton(calibrateButton);
    }

    private void OnCalibrateClicked()
    {
        _ = ShowCalibrationWindowAsync();
    }

    private async Task ShowCalibrationWindowAsync()
    {
        try
        {
            if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop)
            {
                Log.Warning("Avalonia desktop lifetime not available, cannot show calibration window.");
                return;
            }

            var parent = desktop.MainWindow;
            var vm = new CalibrationWindowViewModel(_imageSource, _settings);
            var window = new CalibrationWindow { DataContext = vm };

            if (parent != null)
                await window.ShowDialog(parent);
            else
                window.Show();
        }
        catch (Exception ex)
        {
            Log.Error(ex, "Error showing calibration window");
        }
    }
}
