using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Microsoft.Win32;
using SmartAquaViewer.Controls;
using SmartAquaViewer.Model;

namespace SmartAquaViewer.ViewModel
{
    public class FileListViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<FileModel> FileList { get; set; }

        private FileModel? _selectedFile;
        public FileModel SelectedFile
        {
            get => _selectedFile;
            set
            {
                if (_selectedFile != value)
                {
                    _selectedFile = value;
                    
                    OnPropertyChanged();
                }
            }
        }

        public ICommand OpenFileDialogCommand { get; }

        public FileListViewModel()
        {
            FileList = new ObservableCollection<FileModel>();
            OpenFileDialogCommand = new RelayCommand(OpenFileList);
        }

        private void OpenFileList(object obj)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Multiselect = true,
                Filter = "Json Files (*.json)|*.json|All Files (*.*)|*.*"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                FileList.Clear();

                foreach (var filePath in openFileDialog.FileNames)
                {
                    var fileName = System.IO.Path.GetFileName(filePath);

                    var fileModel = new FileModel { Name = fileName };
                    if (!FileList.Any(f => f.Name == fileModel.Name))
                    {
                        FileList.Add(fileModel);
                    }
                }
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string? name = null)
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}
