# -*- 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
from datetime import datetime

class MassMailingList(models.Model):
    _inherit = "mail.mass_mailing.list"

    @api.multi
    def action_load_enterprise_contacts(self):
        """Load Enterprise Contacts as Recepients on Mailing List
        """
        MailContact_Obj = self.env['mail.mass_mailing.contact']
        
        enterprises = self.env['ecom.ebusiness'].search_read([('id', '>', 0)], ['contacts_line'])        
        contacts = []
        for enterprise in enterprises:
            if enterprise['contacts_line']:
                temp = [contacts.append(x) for x in enterprise['contacts_line']]

        ebusiness_contacts = self.env['ecom.ebusiness.contact'].search_read([('id', 'in', contacts)])
        vals = []
        now = datetime.now()
        for contact in ebusiness_contacts:
            print contact
            if contact.get('send_email', False) and contact.get('email', False):
                recepient = self.env['mail.mass_mailing.contact'].search([('list_id','=',self.id), ('email','=',contact['email'])])
                if not recepient:
                    vals.append({
                            'list_id': self.id,
                            'email': contact['email'],
                            'name': contact.get('display_name', '/'),
                            'create_date': now,
                        })
        if vals:
            for value in vals:
                MailContact_Obj.create(value)