from odoo import _, api, fields, models


class MailQuickTemplatePreviewWizard(models.TransientModel):
    _name = 'mail.quick.template.preview.wizard'
    _description = 'Chatter Quick Reply Template Preview'

    template_id = fields.Many2one(
        'mail.quick.template', string='Template', required=True,
        ondelete='cascade',
    )
    res_model = fields.Char(string='Test Model')
    res_id = fields.Integer(string='Test Record ID')
    resolved_body = fields.Html(
        string='Preview', compute='_compute_resolved_body', sanitize=False,
        readonly=True,
    )
    preview_record_name = fields.Char(
        string='Sample Record', compute='_compute_resolved_body',
        readonly=True,
    )
    attachment_names = fields.Char(
        string='Default Attachments', compute='_compute_resolved_body',
        readonly=True,
    )

    @api.depends('template_id', 'res_model', 'res_id')
    def _compute_resolved_body(self):
        for wiz in self:
            if not wiz.template_id:
                wiz.resolved_body = False
                wiz.preview_record_name = False
                wiz.attachment_names = False
                continue
            wiz.resolved_body = wiz.template_id._resolve_placeholders(
                wiz.res_model, wiz.res_id
            )
            record_name = False
            if wiz.res_model and wiz.res_id and wiz.res_model in self.env:
                rec = self.env[wiz.res_model].browse(wiz.res_id).exists()
                if rec:
                    record_name = rec.display_name
            wiz.preview_record_name = record_name
            wiz.attachment_names = ', '.join(
                wiz.template_id.attachment_ids.mapped('name')
            ) or _('None')
