using CommunityToolkit.Mvvm.Input;
using MangaReader.Core.Search;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;

namespace MangaReader.WinUI.ViewModels;

public partial class SearchViewModel(IMangaSearchCoordinator searchCoordinator) : ViewModelBase
{
    private CancellationTokenSource? _cancellationTokenSource;

    private string? _keyword;

    public string? Keyword
    {
        get
        {
            return _keyword;
        }
        set
        {
            SetProperty(ref _keyword, value);
        }
    }

    private ObservableCollection<MangaSearchResult> _searchResults = [];

    public ObservableCollection<MangaSearchResult> SearchResults
    {
        get
        {
            return _searchResults;
        }
        set
        {
            SetProperty(ref _searchResults, value);
        }
    }

    public ICommand SearchCommand => new AsyncRelayCommand(SearchAsync);

    public async Task SearchAsync()
    {
        if (string.IsNullOrWhiteSpace(Keyword))
            return;

        _cancellationTokenSource?.Cancel();
        _cancellationTokenSource = new();

        Dictionary<string, MangaSearchResult[]> result = await searchCoordinator.SearchAsync(Keyword, _cancellationTokenSource.Token);

        List<MangaSearchResult> searchResults = [];
        
        foreach (var item in result)
        {
            foreach (MangaSearchResult searchResult in item.Value)
            {
                searchResults.Add(searchResult);
            }
        }

        SearchResults = new(searchResults);
    }
}