# -*- 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 MailTemplate(models.Model):
    _inherit = "mail.template"

    @api.multi
    def send_mail(self, res_id, force_send=False, raise_exception=False, email_values=None):
    	"""Format One2many data sent by python function in mail template's body
        - new changes only from Line 33 through 38
    	"""
        self.ensure_one()
        Mail = self.env['mail.mail']
        Attachment = self.env['ir.attachment']  # TDE FIXME: should remove dfeault_type from context
        # create a mail_mail based on values, without attachments
        values = super(MailTemplate, self).generate_email(res_id)
        values['recipient_ids'] = [(4, pid) for pid in values.get('partner_ids', list())]
        values.update(email_values or {})
        attachment_ids = values.pop('attachment_ids', [])
        attachments = values.pop('attachments', [])
        # add a protection against void email_from
        if 'email_from' in values and not values.get('email_from'):
            values.pop('email_from')
        
        #remove &lt; AND &gt; with < > to denote tag:
        context = self.env.context
        if 'ltgt_replace' in context:
            body_html = values['body_html']
            body_html = body_html.replace('&lt;', '<').replace('&gt;', '>')
            values['body_html'] = body_html

        email_from = values.get('email_from', '')
        if email_from and 'enterprise_name' in context:
            email_from = email_from.split('<')[1].split('>')[0]
            email_from = context['enterprise_name'] + ' <' + str(email_from) + '>'
            values['email_from'] = email_from
            
        mail = Mail.create(values)

        # manage attachments
        for attachment in attachments:
            attachment_data = {
                'name': attachment[0],
                'datas_fname': attachment[0],
                'datas': attachment[1],
                'res_model': 'mail.message',
                'res_id': mail.mail_message_id.id,
            }
            attachment_ids.append(Attachment.create(attachment_data).id)
        if attachment_ids:
            values['attachment_ids'] = [(6, 0, attachment_ids)]
            mail.write({'attachment_ids': [(6, 0, attachment_ids)]})

        if force_send:
            mail.send(raise_exception=raise_exception)
        return mail.id  # TDE CLEANME: return mail + api.returns ?
