using System.ComponentModel;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Ehwrj.App.Services;
using Ehwrj.App.ViewModels;
using Ehwrj.Core.Services;

namespace Ehwrj.App;

public partial class MainWindow : Window
{
    private readonly MainViewModel _viewModel;
    private OverlayWindow? _overlayWindow;

    public MainWindow()
    {
        InitializeComponent();

        var settingsStore = new SettingsStore();
        var appSettings = settingsStore.Load();
        var client = new WarThunderClient();
        var processProbe = new ProcessProbe();
        var service = new LiveMapService(client, processProbe);

        _viewModel = new MainViewModel(service, settingsStore, appSettings);
        _viewModel.PropertyChanged += OnViewModelPropertyChanged;
        _viewModel.Settings.Overlay.PropertyChanged += OnOverlaySettingsChanged;
        DataContext = _viewModel;

        Opened += OnOpened;
        Closing += OnClosing;
    }

    private void OnOpened(object? sender, EventArgs e)
    {
        _viewModel.StartCommand.Execute(null);
    }

    private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName is nameof(MainViewModel.IsOverlayEnabled))
        {
            UpdateOverlayVisibility();
        }
    }

    private void OnOverlaySettingsChanged(object? sender, PropertyChangedEventArgs e)
    {
        _overlayWindow?.ApplyBounds();
    }

    private void UpdateOverlayVisibility()
    {
        if (_viewModel.IsOverlayEnabled)
        {
            _overlayWindow ??= new OverlayWindow(_viewModel.Settings.Overlay)
            {
                DataContext = _viewModel
            };
            _overlayWindow.Show();
            _overlayWindow.ApplyBounds();
        }
        else
        {
            _overlayWindow?.Hide();
        }
    }

    private void OnClosing(object? sender, WindowClosingEventArgs e)
    {
        _overlayWindow?.Close();
        _viewModel.Dispose();
    }
}
