using System;
using System.Collections.ObjectModel;
using System.Linq;
using Prism.Mvvm;
using XplorePlane.Services;

namespace XplorePlane.ViewModels
{
    public class OperatorDescriptor
    {
        public string Key { get; }
        public string DisplayName { get; }
        public string IconPath { get; }
        public string Category { get; }

        public OperatorDescriptor(string key, string displayName, string iconPath = "", string category = "通用")
        {
            Key = key;
            DisplayName = displayName;
            IconPath = iconPath;
            Category = category;
        }
    }

    public class OperatorToolboxViewModel : BindableBase
    {
        private readonly IImageProcessingService _imageProcessingService;
        private string _searchText = string.Empty;

        public OperatorToolboxViewModel(IImageProcessingService imageProcessingService)
        {
            _imageProcessingService = imageProcessingService ?? throw new ArgumentNullException(nameof(imageProcessingService));
            AvailableOperators = new ObservableCollection<OperatorDescriptor>();
            FilteredOperators = new ObservableCollection<OperatorDescriptor>();
            LoadOperators();
        }

        public ObservableCollection<OperatorDescriptor> AvailableOperators { get; }
        public ObservableCollection<OperatorDescriptor> FilteredOperators { get; }

        public string SearchText
        {
            get => _searchText;
            set
            {
                if (SetProperty(ref _searchText, value))
                    ApplyFilter();
            }
        }

        private void LoadOperators()
        {
            AvailableOperators.Clear();
            foreach (var key in _imageProcessingService.GetAvailableProcessors())
            {
                var displayName = _imageProcessingService.GetProcessorDisplayName(key);
                AvailableOperators.Add(new OperatorDescriptor(key, displayName ?? key));
            }
            ApplyFilter();
        }

        private void ApplyFilter()
        {
            FilteredOperators.Clear();
            var filtered = string.IsNullOrWhiteSpace(SearchText)
                ? AvailableOperators
                : AvailableOperators.Where(o =>
                    o.DisplayName.Contains(SearchText, StringComparison.OrdinalIgnoreCase));
            foreach (var op in filtered)
                FilteredOperators.Add(op);
        }
    }
}
