# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from odoo.exceptions import UserError


class SoHelpdeskCannedResponse(models.Model):
    _name = 'so.helpdesk.canned.response'
    _description = 'Helpdesk Canned Response'
    _order = 'name'

    name = fields.Char(required=True)
    active = fields.Boolean(default=True)
    team_ids = fields.Many2many(
        comodel_name='so.helpdesk.team',
        relation='so_helpdesk_canned_response_team_rel',
        column1='response_id',
        column2='team_id',
        string='Teams',
        help='Leave empty to make this response available to all teams.',
    )
    subject = fields.Char(string='Email Subject')
    body = fields.Html(string='Response Body', sanitize=True, required=True)

    def action_apply_to_ticket(self):
        """Post canned response body on the active ticket chatter."""
        ticket = self.env['so.helpdesk.ticket'].browse(
            self.env.context.get('active_id')
        )
        if not ticket:
            raise UserError(_('Open a ticket to apply a canned response.'))
        for response in self:
            ticket.message_post(
                body=response.body,
                subject=response.subject or ticket.name,
                message_type='comment',
                subtype_xmlid='mail.mt_comment',
            )
        return True
