using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Microsoft.Win32;
using Newtonsoft.Json;
using SmartAquaViewer.Controls;
using SmartAquaViewer.DataAnalysis;
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();

                    DeserializeContentToJson();
                }
            }
        }

        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)
            {
                foreach (var filePath in openFileDialog.FileNames)
                {
                    var fileName = Path.GetFileName(filePath).Replace(".json", "");
                    var year = int.Parse(fileName.Split("-")[0]);
                    var month = int.Parse(fileName.Split("-")[1]);
                    var day = int.Parse(fileName.Split("-")[2]);
                    var date = new DateTime(year, month, day);

                    var fileModel = new FileModel { Name = fileName, RecordedDate = date };
                    var fileContent = File.ReadAllText(filePath);
                    fileModel.Content = fileContent;

                    if (FileList.Any(f => f.Name == fileModel.Name)) continue;

                    FileList.Add(fileModel);
                    OrderFileListByDate();
                }
            }
        }

        private void DeserializeContentToJson()
        {
            if (SelectedFile == null || string.IsNullOrWhiteSpace(SelectedFile.Content))
                return;

            try
            {
                var list = JsonConvert.DeserializeObject<List<WaterQualityVO>>(SelectedFile.Content)
                           ?? new List<WaterQualityVO>();

                // 여기서 SSOT에 "내용만" 갱신
                Datas.Instance.SetWaterQualityVO(list);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private void OrderFileListByDate()
        {
            var orderedList = FileList.OrderBy(f => f.RecordedDate).ToList();
            FileList.Clear();
            foreach (var file in orderedList)
            {
                FileList.Add(file);
            }
        }

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