using ReAct_PME.WPF_FrameWork;
using Services;
using Services.ReActAgent;
using System.Collections.ObjectModel;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Windows.Threading;
using ToolsServices;

namespace ReAct_PME.ViewModels
{
    public class ListeEmailsSend_VM : BaseViewModel
    {
        #region Variables
        private readonly string TxtTitreFenetreOpenSubjects   = "Conversations en cours : ";
        private readonly string TxtTitreFenetreClosedSubjects = "Conversations archivées : ";

        private readonly string TxtShowOpenSubjectsContent   = "Voir les conversations en cours";
        private readonly string TxtShowClosedSubjectsContent = "Voir les conversations archivées";

        private Services.ThreadStore store = new();
        private readonly DispatcherTimer _emailCheckTimerStart;
        private readonly DispatcherTimer _emailCheckTimer;
        private readonly CompteMailUser _ParametresUser = new();
        private readonly IToastNotifier _Notifier;
        #endregion

        #region Propriétés
        public string TitreFenetre { get; set; } = "";
        public ObservableCollection<ThreadItem>? ListeItems { get; set; } = [];
        private ThreadItem? _selectedItem;
        public ThreadItem? SelectedItem
        {
            get => _selectedItem;
            set
            {
                if (_selectedItem != value)
                {
                    _selectedItem = value;
                    OnPropertyChanged();
                }
            }
        }

        public string TxtBtnShowClosed { get; set; } = "";
        public bool IsShowClosedSubjects { get; set; } = false;
        #endregion

        #region Constructeur
        public ListeEmailsSend_VM(IToastNotifier notifier)
        {
            _Notifier = notifier;

            LoadData();

            var paramUser = Services.EmailService.LoadParametres();
            if (paramUser != null)
            {
                _ParametresUser = paramUser;
            }

            // 1 minute après le chargement, on lance une première récup (une seule fois)
            _emailCheckTimerStart = new DispatcherTimer
            {
                Interval = TimeSpan.FromMinutes(15)
            };
            _emailCheckTimerStart.Tick += async (s, e) => await CheckForNewEmails();
            _emailCheckTimerStart.Start();

            // On programme une récup récurente toutes les x minutes
            _emailCheckTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMinutes(_ParametresUser.DelaySentRefresh)
            };
            _emailCheckTimer.Tick += async (s, e) => await CheckForNewEmails();
            _emailCheckTimer.Start();
        }
        #endregion

        #region Méthodes publiques

        private bool IsTraitementActif = false;
        public async Task CheckForNewEmails()
        {
            LoggerService.LogInfo("ListeEmailsSend_VM.CheckForNewEmails");
            if( IsTraitementActif ) 
            {
                LoggerService.LogDebug("ListeEmailsSend_VM.CheckForNewEmails : Un traitement est déjà en cours. On ne relance pas.");
                return;
            }
            IsTraitementActif = true;

            var b1 = await ReActAgent.IsOllamaActif(false);
            if (!b1)
            {
                var msg1 = "Ollama n'est pas démarré. Veuillez lancer Ollama Desktop ou le service Ollama.";
                LoggerService.LogWarning(msg1);
                _Notifier.ShowToast($"{msg1}", 5000);
                return;
            }
            try
            {
                _emailCheckTimerStart.Stop();
                _emailCheckTimer.Stop();

                var (b2, msg2, nbConvOpened) = await EmailSendService.RunOnce(_ParametresUser);
                if (b2)
                {
                    var txt = "";
                    LoadData();
                    if (nbConvOpened > 0)
                    {
                        var pls = (nbConvOpened > 1) ? "s" : "";
                        var a_ont = (nbConvOpened > 1) ? "ont" : "a";
                        txt = $"\n{nbConvOpened} conversation{pls} {a_ont} été ré-ouverte{pls} car une relance a été générée";
                    }
                    _Notifier.ShowToast($"Liste des conversations rafraîchie...{txt}", 2000);
                }
                else
                {
                    _Notifier.ShowToast($"Erreur : {msg2}", 5000);
                }
            }
            catch (Exception ex) 
            {
                LoggerService.LogError($"{ex.Message}");
                //_Notifier.ShowToast($"Erreur : {ex.Message}", 5000);
            }
            finally 
            {
                _emailCheckTimer.Start();
                IsTraitementActif = false;
            }
        }

        public void SaveThreadItem(ThreadItem thread)
        {
            Services.EmailSendService.Save(thread);
        }

        public void CloseConversation()
        {
            if (SelectedItem != null)
            {
                SelectedItem.SubjectClosed = !SelectedItem.SubjectClosed;
                LoggerService.LogInfo($"ListeEmailsSend_VM.CloseConversation : {SelectedItem.SubjectClosed} --> {SelectedItem.Subject}");
                EmailSendService.Save(SelectedItem);
                LoadData();
            }
        }

        public void ShowConversation()
        {
            LoadData();
        }

        #endregion

        #region Méthodes privées
        private void LoadData()
        {

            /*
            var fileMailsSend = FichiersInternesService.ListeMailsSend;
            if (File.Exists(fileMailsSend))
            {
                var json = System.IO.File.ReadAllText(fileMailsSend);
                store = JsonSerializer.Deserialize<ThreadStore>(json) ?? new ThreadStore();
            }
            */
            store = Services.EmailSendService.ChargerDonnees();
            ListeItems = new ObservableCollection<ThreadItem>(store.Threads.Where(e => e.SubjectClosed == IsShowClosedSubjects).OrderByDescending(e => e.DateMessage).ToList());
            OnPropertyChanged(nameof(ListeItems));

            TxtBtnShowClosed = IsShowClosedSubjects ? TxtShowOpenSubjectsContent : TxtShowClosedSubjectsContent;
            OnPropertyChanged(nameof(TxtBtnShowClosed));

            var txtPluriel = ListeItems.Count > 1 ? "s" : "";
            TitreFenetre = IsShowClosedSubjects ? TxtTitreFenetreClosedSubjects : TxtTitreFenetreOpenSubjects;
            TitreFenetre += " " + ListeItems.Count + $" conversation{txtPluriel}";
            OnPropertyChanged(nameof(TitreFenetre));


            //ThreadsList.ItemsSource = lst;
        }
        #endregion

    }
}
