using Avalonia.Collections;
using Avalonia.Controls;
using Avalonia.Interactivity;
using CommunityToolkit.Mvvm.DependencyInjection;
using Dock.Avalonia.Controls;
using Dock.Model;
using Dock.Model.Controls;
using Dock.Model.Core;
using Dock.Serializer;
using PSCHelpdesk.Shared.Service;
using PSCHelpdesk.Shared.Setting;
using PSCHelpdesk.ViewModels;

namespace PSCHelpdesk.Views;

public partial class MainDockWindow : Window
{

    private readonly IDockState _dockState;
    private readonly IDockSerializer _serializer;
    
    public MainDockWindow()
    {
        _serializer = new DockSerializer(typeof(AvaloniaList<>));
        this.DataContext = new MainDockWindowViewModel();
        InitializeComponent();
        
        _dockState = new DockState();

        if (Dock is { })
        {
            var layout = Dock.Layout;
            if (layout is { })
            {
                _dockState.Save(layout);
            }
        }
       
        (this.DataContext as MainDockWindowViewModel).openTab += (_, e) =>
        {
           
        };
        
        (this.DataContext as MainDockWindowViewModel).SaveHandler += (_, __) =>
        {
            var settingsManager = (SettingsManager)Ioc.Default.GetService<ISettingsManager>();
            var dock = this.FindControl<DockControl>("Dock");
            if (dock?.Layout is { })
            {
                settingsManager.SaveLayoutModels(dock.Layout);
            }
        };
        
        (this.DataContext as MainDockWindowViewModel).LoadHandler += (_, __) =>
        {
            var settingsManager = (SettingsManager)Ioc.Default.GetService<ISettingsManager>();
            var dock = this.FindControl<DockControl>("Dock");
            if (dock is { })
            {
                var layout = settingsManager.LoadLayoutModels();

                if (layout is { })
                {
                    //dock.Layout = layout;
                    (this.DataContext as MainDockWindowViewModel).Layout = (IRootDock)layout;
                    _dockState.Restore(layout);
                }
                
            }
        };
    }
    
    private void Exit_OnClick(object? sender, RoutedEventArgs e)
    {
        Close();
    }

    private void Settings_OnClick(object? sender, RoutedEventArgs e)
    {
        SettingsWindow settings = new SettingsWindow
        {
            DataContext = new SettingsViewModel(),
            Width = 800,
            Height = 600
        };
        settings.Show();
    }
}