using System.Reactive;
using CommunityToolkit.Mvvm.DependencyInjection;
using DynamicData;
using FastBill.Models;
using FastBill.Services;
using PSCHelpdesk.Shared.Service;
using PSCHelpdesk.Shared.Setting;
using PSCHelpdesk.Shared.ViewModels;
using ReactiveUI;

namespace FastBill.ViewModels;

public class CustomerViewModel: ViewModelBase, IViewModelBase
{
    private string _term;
    
    private List<Customer> _customers;
    
    public string Term
    {
        get => _term;
        set => SetAndRaisePropertyChanged(ref _term, value);
    }
    
    public List<Customer> Customers
    {
        get => _customers;
        set => SetAndRaisePropertyChanged(ref _customers, value);
    }

    
    private CustomerService _customerService;
    private readonly SettingsManager? _settingsManager;

    public ReactiveCommand<Unit, Unit> SearchCustomer { get; }

    public CustomerViewModel(CustomerService customerService)
    {
        Title = "Kunden";
        Term = "";
        _customerService = customerService;
        SearchCustomer = ReactiveCommand.Create(searchTerm);
        _settingsManager = (SettingsManager)Ioc.Default.GetService<ISettingsManager>();
    }
    async void searchTerm()
    {
        Customers = await _customerService.SearchCustomer(Term);
        var settings = new Settings();
        _settingsManager.LoadPluginSettings("FastbillSettings", settings);
        foreach (var customer in Customers)
        {
            customer.Contacts = await _customerService.GetContacts(customer.Id);
            
            if (settings.Customers.Count(x => x.Id == customer.Id) > 0)
            {
                var index = settings.Customers.FindIndex(x => x.Id == customer.Id);
                settings.Customers[index] = customer;
            }
            else
            {
                settings.Customers.Add(customer);
            }
        }
        
        _settingsManager.SavePluginSettings("FastbillSettings", settings);
    }
}