# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models
from odoo.exceptions import UserError


class MailTemplatePreview(models.TransientModel):
    _name = 'mail.template.preview'
    _description = 'Email Template Preview'
    _MAIL_TEMPLATE_FIELDS = ['attachment_ids',
                             'body_html',
                             'subject',
                             'email_cc',
                             'email_from',
                             'email_to',
                             'partner_to',
                             'report_template_ids',
                             'reply_to',
                             'scheduled_date',
                            ]

    @api.model
    def _selection_target_model(self):
        return [(model.model, model.name) for model in self.env['ir.model'].sudo().search([])]

    @api.model
    def _selection_languages(self):
        return self.env['res.lang'].get_installed()


    mail_template_id = fields.Many2one('mail.template', string='Related Mail Template', required=True)
    model_id = fields.Many2one('ir.model', string='Targeted model', related="mail_template_id.model_id")
    resource_ref = fields.Reference(
        string='Record',
        compute='_compute_resource_ref',
        compute_sudo=False, readonly=False,
        selection='_selection_target_model',
        store=True
    )
    lang = fields.Selection(_selection_languages, string='Template Preview Language', default=lambda self: self.env.user.lang)
    no_record = fields.Boolean('No Record', compute='_compute_no_record')
    error_msg = fields.Char('Error Message', compute='_compute_mail_template_fields')
    # Fields same than the mail.template model, computed with resource_ref and lang
    subject = fields.Char('Subject', compute='_compute_mail_template_fields')
    email_from = fields.Char('From', compute='_compute_mail_template_fields', help="Sender address")
    email_to = fields.Char('To', compute='_compute_mail_template_fields',
                           help="Comma-separated recipient addresses")
    email_cc = fields.Char('Cc', compute='_compute_mail_template_fields', help="Carbon copy recipients")
    reply_to = fields.Char('Reply-To', compute='_compute_mail_template_fields', help="Preferred response address")
    scheduled_date = fields.Char('Scheduled Date', compute='_compute_mail_template_fields',
                                 help="The queue manager will send the email after the date")
    body_html = fields.Html('Body', compute='_compute_mail_template_fields', sanitize=False)
    attachment_ids = fields.Many2many('ir.attachment', string='Attachments', compute='_compute_mail_template_fields')
    has_attachments = fields.Boolean(compute='_compute_has_attachments')
    has_several_languages_installed = fields.Boolean(compute='_compute_has_several_languages_installed')
    recipient_names = fields.Char('Recipient Names', compute='_compute_mail_template_fields',
                                help="Names of the recipients")
    # Extra fields info generated by _generate_template
    partner_ids = fields.Many2many('res.partner', string='Recipients', compute='_compute_mail_template_fields')

    @api.depends('model_id')
    def _compute_no_record(self):
        for preview, preview_sudo in zip(self, self.sudo()):
            model_id = preview_sudo.model_id
            preview.no_record = not model_id or not self.env[model_id.model].search_count([])

    @api.depends('lang', 'resource_ref')
    def _compute_mail_template_fields(self):
        """ Preview the mail template (body, subject, ...) depending of the language and
        the record reference, more precisely the record id for the defined model of the mail template.
        If no record id is selectable/set, the inline_template placeholders won't be replace in the display information. """
        for preview in self:
            error_msg = False
            mail_template = preview.mail_template_id.with_context(lang=preview.lang)
            if not preview.resource_ref or not preview.resource_ref.id:
                preview._set_mail_attributes()
                preview.error_msg = False
            else:
                try:
                    mail_values = mail_template.with_context(template_preview_lang=preview.lang)._generate_template(
                        [preview.resource_ref.id],
                        preview._MAIL_TEMPLATE_FIELDS
                    )[preview.resource_ref.id]

                    if mail_template.email_layout_xmlid:
                        # Encapsulate body with layout
                        msg_vals = {
                            'author_id': preview.env.user.partner_id.id,
                            'body': mail_values['body_html'],
                            # Templates include signature in the body
                            'email_add_signature': False,
                            'email_layout_xmlid': mail_template.email_layout_xmlid,
                            'model': preview.model_id.model,
                            # If no partners, then show it for current user
                            'partner_ids': mail_values.get('partner_ids', preview.env.user.partner_id.ids),
                            'record_name': preview.resource_ref.display_name,
                            'res_id': preview.resource_ref.id,
                        }
                        ActiveModel = preview.resource_ref if isinstance(preview.resource_ref, preview.pool["mail.thread"]) else preview.env["mail.thread"]
                        # Create a message without db entry for the layout.
                        message = preview.env['mail.message'].new(msg_vals)
                        recipients_data = ActiveModel._notify_get_recipients(message, msg_vals, notify_author=True)
                        if not recipients_data:
                            # Append a dummy recipient to ensure the layout is rendered
                            recipients_data.append({
                                'active': True,
                                'email_normalized': False,
                                'id': 0,
                                'is_follower': False,
                                'lang': preview.env.lang,
                                'groups': [],
                                'notif': 'email',
                                'share': True,
                                'type': 'customer',
                                'uid': None,
                                'ushare': False,
                            })
                        _lang, render_values, recipients_group = next(
                            ActiveModel._notify_get_classified_recipients_iterator(
                                message,
                                recipients_data,
                                msg_vals=msg_vals,
                                force_header=mail_template.email_layout_force_header,
                                force_footer=mail_template.email_layout_force_footer,
                            )
                        )
                        mail_values['body_html'] = (
                            ActiveModel._notify_by_email_render_layout(
                                message,
                                recipients_group,
                                msg_vals=msg_vals,
                                render_values=render_values,
                            )
                        )
                    # Link attachments generated by _generate_template
                    if mail_values['attachments']:
                        mail_values['attachment_ids'] += preview.env['ir.attachment'].create([
                            {
                                'name': attach_fname,
                                'datas': attach_datas,
                                'res_model': 'mail.template.preview',
                                'res_id': preview.id,
                                'type': 'binary',
                            } for attach_fname, attach_datas in mail_values['attachments']
                        ]).ids

                    preview._set_mail_attributes(values=mail_values)
                except (ValueError, UserError) as user_error:
                    preview._set_mail_attributes()
                    error_msg = user_error.args[0]
            preview.error_msg = error_msg

    @api.depends('attachment_ids')
    def _compute_has_attachments(self):
        for preview in self:
            preview.has_attachments = bool(preview.attachment_ids)

    @api.depends('lang')
    def _compute_has_several_languages_installed(self):
        for preview in self:
            preview.has_several_languages_installed = len(preview._fields['lang'].selection(preview)) > 1

    @api.autovacuum
    def _gc_preview_attachments(self):
        """ Remove attachments generated by the preview wizard. """
        limit_date = fields.Datetime.subtract(fields.Datetime.now(), days=1)
        self.env['ir.attachment'].search([
            ('res_model', '=', 'mail.template.preview'),
            ('create_date', '<', limit_date),
            ('write_date', '<', limit_date)],
        ).unlink()

    @api.depends('mail_template_id')
    def _compute_resource_ref(self):
        to_reset = self.filtered(lambda p: not p.mail_template_id.model)
        to_reset.resource_ref = False
        for preview in (self - to_reset):
            mail_template = preview.mail_template_id.sudo()
            model = mail_template.model
            res = self.env[model].search([], limit=1)
            preview.resource_ref = f'{model},{res.id}' if res else False

    def _set_mail_attributes(self, values=None):
        for field in self._MAIL_TEMPLATE_FIELDS:
            if field in ('partner_to', 'report_template_ids'):
                # partner_to is used to generate partner_ids, handled here below
                # report_template_ids generates attachments, no usage here
                continue
            field_value = values.get(field, False) if values else self.mail_template_id[field]
            self[field] = field_value
        self.partner_ids = values.get('partner_ids', False) if values else False
        self.recipient_names = ", ".join(
            [partner.email_formatted or partner.name for partner in self.partner_ids] +
            [values[field] for field in ("email_to", "email_cc") if values and values.get(field)]
        )
