using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive;
using Avalonia.Controls;
using CommunityToolkit.Mvvm.DependencyInjection;
using PSCHelpdesk.Services;
using PSCHelpdesk.Shared.Menu;
using PSCHelpdesk.Shared.Service;
using PSCHelpdesk.Shared.ViewModels;
using ReactiveUI;

namespace PSCHelpdesk.ViewModels;

public class MainWindowViewModel : ViewModelBase, IViewModelBase
{
    private MenuService MenuService;
    public ReactiveCommand<string, Unit> ClickMenu { get; }
    private ObservableCollection<TabItemViewModel> _tabItems;
    
    public ObservableCollection<TabItemViewModel> TabItems
    {
        get => _tabItems;
        set => SetAndRaisePropertyChanged(ref _tabItems, value);
    }

    private List<Item> _menuItems;
    public List<Item> MenuItems
    {
        get => _menuItems;
        set => SetAndRaisePropertyChanged(ref _menuItems, value);
    }
    
    
    public MainWindowViewModel()
    {
        Startup.RegisterServices();
        ClickMenu = ReactiveCommand.Create<string>(SelectMenu);
        TabItems = new ObservableCollection<TabItemViewModel>();
        this.MenuItems = new List<Item>();
        MenuService = (MenuService)Ioc.Default.GetService(typeof(IMenuService));
        MenuService.MenuChanged += delegate(object? sender, EventArgs args)
        {
            foreach (var menuServiceMenuItem in MenuService.MenuItems)
            {
                if (!this.MenuItems.Contains(menuServiceMenuItem))
                {
                    menuServiceMenuItem.Command = this.ClickMenu;
                    this.MenuItems.Add(menuServiceMenuItem);
                }

                if (TabItems.Count == 0)
                {
                    TabItems.Add(new TabItemViewModel(MenuItems.Last().Header, MenuItems.Last().CommandParameter));    
                }
            }
            
            foreach (var menuServiceMenuItem in MenuService.MenuOptionItems)
            {
                if (!this.MenuItems.Contains(menuServiceMenuItem))
                {
                    menuServiceMenuItem.Command = this.ClickMenu;
                    this.MenuItems.Add(menuServiceMenuItem);
                }
            }
        };
            
        this.InitializeClient();
    }
    
    private void InitializeClient()
    {
        this.MenuService.CreateMenu();
    }
    
    public void SelectMenu(string parameter)
    {
        //this.SelectedItem = parameter;
        var obj = this.MenuService.MenuItems.FirstOrDefault(menuItem => menuItem.Header == parameter.ToString(), null);
        if (obj != null)
        {
            if (TabItems.Count(x => x.Header == obj.Header) == 0)
            {
                TabItems.Add(new TabItemViewModel(obj.Header, obj.CommandParameter));
            }
        }
    }
    
}