<commit_before>﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net.Configuration;
using System.Text;
using Signum.Engine.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Entities;
using Signum.Entities.DynamicQuery;
using Signum.Entities.Mailing;
using Signum.Utilities;
using Signum.Entities.Translation;
using Signum.Engine.Translation;
using Signum.Engine.Mailing;

namespace Signum.Engine.Mailing
{
    class EmailMessageBuilder
    {
        EmailTemplateEntity template;
        IEntity entity;
        ISystemEmail systemEmail;
        object queryName;
        QueryDescription qd;
        SmtpConfigurationEntity smtpConfig;

        public EmailMessageBuilder(EmailTemplateEntity template, IEntity entity, ISystemEmail systemEmail)
        {
            this.template = template;
            this.entity = entity;
            this.systemEmail = systemEmail;

            this.queryName = QueryLogic.ToQueryName(template.Query.Key);
            this.qd = DynamicQueryManager.Current.QueryDescription(queryName);
            this.smtpConfig = EmailTemplateLogic.GetSmtpConfiguration == null ? null : EmailTemplateLogic.GetSmtpConfiguration(template);
        }

        ResultTable table;
        Dictionary<QueryToken, ResultColumn> dicTokenColumn;
        IEnumerable<ResultRow> currentRows;


        public IEnumerable<EmailMessageEntity> CreateEmailMessageInternal()
        {
            ExecuteQuery();

            foreach (EmailAddressEntity from in GetFrom())
            {
                foreach (List<EmailOwnerRecipientData> recipients in GetRecipients())
                {
                    CultureInfo ci = recipients.Where(a => a.Kind == EmailRecipientKind.To).Select(a => a.OwnerData.CultureInfo).FirstOrDefault().ToCultureInfo();

                    EmailMessageEntity email = new EmailMessageEntity
                    {
                        Target = (Lite<Entity>)entity.ToLite(),
                        Recipients = recipients.Select(r => new EmailRecipientEntity(r.OwnerData) { Kind = r.Kind }).ToMList(),
                        From = from,
                        IsBodyHtml = template.IsBodyHtml,
                        EditableMessage = template.EditableMessage,
                        Template = template.ToLite(),
                        Attachments = template.Attachments.SelectMany(g => EmailTemplateLogic.GenerateAttachment.Invoke(g, new EmailTemplateLogic.GenerateAttachmentContext
                        {
                            QueryDescription = this.qd,
                            ModelType = template.SystemEmail.ToType(),
                            SystemEmail = systemEmail,
                            CurrentRows = currentRows,
                            ResultColumns = dicTokenColumn,
                            Entity = entity, 
                            Template = template,
                            Culture = ci ?? EmailLogic.Configuration.DefaultCulture.ToCultureInfo(),
                        })).ToMList()
                    };

                    
                    EmailTemplateMessageEntity message = template.GetCultureMessage(ci) ?? template.GetCultureMessage(EmailLogic.Configuration.DefaultCulture.ToCultureInfo());

                    if (message == null)
                        throw new InvalidOperationException("Message {0} does not have a message for CultureInfo {1} (or Default)".FormatWith(template, ci));

                    email.Subject = SubjectNode(message).Print(
                        new EmailTemplateParameters(entity, ci, dicTokenColumn, currentRows)
                        {
                            IsHtml = false,
                            SystemEmail = systemEmail
                        });

                    email.Body = TextNode(message).Print(
                        new EmailTemplateParameters(entity, ci, dicTokenColumn, currentRows)
                        {
                            IsHtml = template.IsBodyHtml,
                            SystemEmail = systemEmail,
                        });


                    yield return email;
                }
            }
        }

        EmailTemplateParser.BlockNode TextNode(EmailTemplateMessageEntity message)
        {
            if (message.TextParsedNode == null)
            {
                string body = message.Text;

                if (template.MasterTemplate != null)
                {
                    var emt = template.MasterTemplate.Retrieve();<commit_msg>fix language in EmailTemplateRenderer<commit_after>﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net.Configuration;
using System.Text;
using Signum.Engine.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Entities;
using Signum.Entities.DynamicQuery;
using Signum.Entities.Mailing;
using Signum.Utilities;
using Signum.Entities.Translation;
using Signum.Engine.Translation;
using Signum.Engine.Mailing;

namespace Signum.Engine.Mailing
{
    class EmailMessageBuilder
    {
        EmailTemplateEntity template;
        IEntity entity;
        ISystemEmail systemEmail;
        object queryName;
        QueryDescription qd;
        SmtpConfigurationEntity smtpConfig;

        public EmailMessageBuilder(EmailTemplateEntity template, IEntity entity, ISystemEmail systemEmail)
        {
            this.template = template;
            this.entity = entity;
            this.systemEmail = systemEmail;

            this.queryName = QueryLogic.ToQueryName(template.Query.Key);
            this.qd = DynamicQueryManager.Current.QueryDescription(queryName);
            this.smtpConfig = EmailTemplateLogic.GetSmtpConfiguration == null ? null : EmailTemplateLogic.GetSmtpConfiguration(template);
        }

        ResultTable table;
        Dictionary<QueryToken, ResultColumn> dicTokenColumn;
        IEnumerable<ResultRow> currentRows;


        public IEnumerable<EmailMessageEntity> CreateEmailMessageInternal()
        {
            ExecuteQuery();

            foreach (EmailAddressEntity from in GetFrom())
            {
                foreach (List<EmailOwnerRecipientData> recipients in GetRecipients())
                {
                    CultureInfo ci = recipients.Where(a => a.Kind == EmailRecipientKind.To).Select(a => a.OwnerData.CultureInfo).FirstOrDefault().ToCultureInfo() ?? EmailLogic.Configuration.DefaultCulture.ToCultureInfo();

                    EmailMessageEntity email = new EmailMessageEntity
                    {
                        Target = (Lite<Entity>)entity.ToLite(),
                        Recipients = recipients.Select(r => new EmailRecipientEntity(r.OwnerData) { Kind = r.Kind }).ToMList(),
                        From = from,
                        IsBodyHtml = template.IsBodyHtml,
                        EditableMessage = template.EditableMessage,
                        Template = template.ToLite(),
                        Attachments = template.Attachments.SelectMany(g => EmailTemplateLogic.GenerateAttachment.Invoke(g, new EmailTemplateLogic.GenerateAttachmentContext
                        {
                            QueryDescription = this.qd,
                            ModelType = template.SystemEmail.ToType(),
                            SystemEmail = systemEmail,
                            CurrentRows = currentRows,
                            ResultColumns = dicTokenColumn,
                            Entity = entity, 
                            Template = template,
                            Culture = ci,
                        })).ToMList()
                    };
                    
                    EmailTemplateMessageEntity message = template.GetCultureMessage(ci) ?? template.GetCultureMessage(EmailLogic.Configuration.DefaultCulture.ToCultureInfo());

                    if (message == null)
                        throw new InvalidOperationException("Message {0} does not have a message for CultureInfo {1} (or Default)".FormatWith(template, ci));

                    using (CultureInfoUtils.ChangeBothCultures(ci))
                    {
                        email.Subject = SubjectNode(message).Print(
                            new EmailTemplateParameters(entity, ci, dicTokenColumn, currentRows)
                            {
                                IsHtml = false,
                                SystemEmail = systemEmail
                            });

                        email.Body = TextNode(message).Print(
                            new EmailTemplateParameters(entity, ci, dicTokenColumn, currentRows)
                            {
                                IsHtml = template.IsBodyHtml,
                                SystemEmail = systemEmail,
                            });
                    }


                    yield return email;
                }
            }
        }

        EmailTemplateParser.BlockNode TextNode(EmailTemplateMessageEntity message)
        {
            if (message.TextParsedNode == null)
            {
                string body = message.Text;

                if (template.MasterTemplate != null)
                {
                    var emt = template.MasterTemplate.Retrieve();
{'fraction_non_alphanumeric': 0.07307651035518832, 'fraction_numerical': 0.00042923060414207535, 'mean_word_length': 1.6583000570450657, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2978230', 'n_tokens_mistral': 2122, 'n_tokens_neox': 2022, 'n_words': 410}