using ToolsServices;
using Services;
using ReAct_PME.WPF_FrameWork;

namespace ReAct_PME.ViewModels
{
    public class DetailEmail_VM : BaseViewModel
    {
        public EmailMessage? SelectedItem { get; set; } = new();
        public DetailEmail_VM(EmailMessage? selectedItem)
        {
            SelectedItem = selectedItem;
        }

        public string? NbrPJ
        {
            get
            {
                if(!SelectedItem!.IsPJ)
                    return "Sans PJ";
                return $"Nbre de PJ : {SelectedItem.ContentPJ!.Count}";
            }
        }

        public async Task<bool> EnvoyerReponse()
        {
            try
            {
                string messageBody = $"""
                    {SelectedItem!.Reponse}

                    ....

                    {SelectedItem!.TextBody}
                    """;

                var b = await Services.EmailService.EnvoyerMailAsync(
                    SelectedItem!.Uid,
                    SelectedItem!.From,
                    SelectedItem!.Subject,
                    messageBody,
                    true,
                    SelectedItem.Id
                );

                if(b)
                {
                    SelectedItem!.ToRemove = true;
                }

                return b;
            }
            catch (Exception ex)
            {
                LoggerService.LogError( ex.ToString() );
                return false;
            }
        }

        public async Task<bool> MarquerLu()
        {
            var b = await Services.EmailService.MaquerLu(SelectedItem!.Uid);
            if (b)
            {
                SelectedItem!.ToRemove = true;
            }
            return b;
        }

        public async Task<bool> GenerateAgainReponse()
        {
            await Task.Delay(1);
            var context = new List<ContextGeneration>();
            context.Add(new ContextGeneration { Name = "Type de mail", Description = "Mail reçu" });
            context.Add(new ContextGeneration { Name = "Contenu du mail reçu", Description = SelectedItem!.TextBody });
            context.Add(new ContextGeneration { Name = "Catégorie du mail", Description = SelectedItem!.Categorie });
            context.Add(new ContextGeneration { Name = "Stratégie de réponse", Description = SelectedItem!.Strategie });
            var f = new _ModalGenerateAgain(SelectedItem!.Reponse!, context);
            f.ShowDialog();
            if (f.IsOk)
            {
                SelectedItem.Reponse = f.ReponseNew;
                OnPropertyChanged(nameof(SelectedItem));
                return true;
            }
            return false;
        }
    }
}
