# -*- coding: utf-8 -*-
##############################################################################
#
#    Odoo, Open Source Management Solution
#    Copyright (C) 2016-TODAY Prime Consulting SA, Cape Verde (<http://prime.cv>).
#
##############################################################################
from odoo import models, fields, api, _

class Invite(models.TransientModel):
    _inherit = 'mail.wizard.invite'

    @api.multi
    def add_followers(self):
        """Overwrite function to restrict auto adding of customer as follower on Quotation / Sales Order when other user is added as follower.
        """
        email_from = self.env['mail.message']._get_default_from()
        for wizard in self:
            Model = self.env[wizard.res_model]
            document = Model.browse(wizard.res_id)

            # filter partner_ids to get the new followers, to avoid sending email to already following partners
            new_partners = wizard.partner_ids - document.message_partner_ids
            new_channels = wizard.channel_ids - document.message_channel_ids
            
            document.message_subscribe(new_partners.ids, new_channels.ids)

            model_ids = self.env['ir.model'].search([('model', '=', wizard.res_model)])
            model_name = model_ids.name_get()[0][1]
            # send an email if option checked and if a message exists (do not send void emails)
            if wizard.send_mail and wizard.message and not wizard.message == '<br>':  # when deleting the message, cleditor keeps a <br>
                message = self.env['mail.message'].create({
                    'subject': _('Invitation to follow %s: %s') % (model_name, document.name_get()[0][1]),
                    'body': wizard.message,
                    'record_name': document.name_get()[0][1],
                    'email_from': email_from,
                    'reply_to': email_from,
                    'model': wizard.res_model,
                    'res_id': wizard.res_id,
                    'no_auto_thread': True,
                })
                #custom: add context key to check original followers list
                new_partners.with_context(auto_delete=True, new_partners=new_partners)._notify(message, force_send=True, send_after_commit=False, user_signature=True)
                message.unlink()
        return {'type': 'ir.actions.act_window_close'}

class Followers(models.Model):
    
    _inherit = 'mail.followers'

    @api.model
    def create(self, vals):
        context = self.env.context or dict()
        if context.get('new_partners', False) and 'partner_id' in vals:
            if vals['partner_id'] not in context['new_partners'].ids:
                return False
        return super(Followers, self).create(vals)
