1# -*- coding: utf-8 -*-
2# Part of Odoo. See LICENSE file for full copyright and licensing details.
3
4from odoo import api, fields, models
5
6
7class CalendarEvent(models.Model):
8    _inherit = 'calendar.event'
9
10    @api.model
11    def default_get(self, fields):
12        if self.env.context.get('default_opportunity_id'):
13            self = self.with_context(
14                default_res_model_id=self.env.ref('crm.model_crm_lead').id,
15                default_res_id=self.env.context['default_opportunity_id']
16            )
17        defaults = super(CalendarEvent, self).default_get(fields)
18
19        # sync res_model / res_id to opportunity id (aka creating meeting from lead chatter)
20        if 'opportunity_id' not in defaults:
21            if self._is_crm_lead(defaults, self.env.context):
22                defaults['opportunity_id'] = defaults.get('res_id', False) or self.env.context.get('default_res_id', False)
23
24        return defaults
25
26    opportunity_id = fields.Many2one(
27        'crm.lead', 'Opportunity', domain="[('type', '=', 'opportunity')]",
28        index=True, ondelete='set null')
29
30    def _compute_is_highlighted(self):
31        super(CalendarEvent, self)._compute_is_highlighted()
32        if self.env.context.get('active_model') == 'crm.lead':
33            opportunity_id = self.env.context.get('active_id')
34            for event in self:
35                if event.opportunity_id.id == opportunity_id:
36                    event.is_highlighted = True
37
38    @api.model_create_multi
39    def create(self, vals):
40        events = super(CalendarEvent, self).create(vals)
41        for event in events:
42            if event.opportunity_id and not event.activity_ids:
43                event.opportunity_id.log_meeting(event.name, event.start, event.duration)
44        return events
45
46    def _is_crm_lead(self, defaults, ctx=None):
47        """
48            This method checks if the concerned model is a CRM lead.
49            The information is not always in the defaults values,
50            this is why it is necessary to check the context too.
51        """
52        res_model = defaults.get('res_model', False) or ctx and ctx.get('default_res_model')
53        res_model_id = defaults.get('res_model_id', False) or ctx and ctx.get('default_res_model_id')
54
55        return res_model and res_model == 'crm.lead' or res_model_id and self.env['ir.model'].sudo().browse(res_model_id).model == 'crm.lead'
56