# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo.addons.website_form.controllers.main import WebsiteForm
from odoo import http
from odoo.http import request

import base64

class WebsiteFormExtension(WebsiteForm):

    # Extract all data sent by the form and sort its on several properties
    def extract_data(self, model, values):
        data = super(WebsiteFormExtension, self).extract_data(model, values)

        if model and model.model == 'mail.mail':
            for field_name, field_value in values.items():
                # set subject using field named email_subject
                if field_name == 'email_subject':
                    data['record']['subject'] = field_value

        return data

    # Link all files attached on the form
    def insert_attachment(self, model, id_record, files):
        orphan_attachment_ids = []
        record = model.env[model.model].browse(id_record)
        authorized_fields = model.sudo()._get_form_writable_fields()
        for file in files:
            custom_field = file.field_name not in authorized_fields
            attachment_value = {
                'name': file.field_name if custom_field else file.filename,
                'datas': base64.encodestring(file.read()),
                'datas_fname': file.filename,
                'res_model': model.model,
                'res_id': record.id,
            }
            attachment_id = request.env['ir.attachment'].sudo().create(attachment_value)
            if attachment_id and not custom_field:
                record.sudo()[file.field_name] = [(4, attachment_id.id)]
            else:
                orphan_attachment_ids.append(attachment_id.id)

        # If some attachments didn't match a field on the model,
        # we create a mail.message to link them to the record
        if orphan_attachment_ids:
            if model.model != 'mail.mail':
                values = {
                    'body': _('<p>Attached files : </p>'),
                    'model': model.model,
                    'message_type': 'comment',
                    'no_auto_thread': False,
                    'res_id': id_record,
                    'attachment_ids': [(6, 0, orphan_attachment_ids)],
                }
                mail_id = request.env['mail.message'].sudo().create(values)
            else:
                # If the model is mail.mail then we have no other choice but to
                # attach the custom binary field files on the attachment_ids field.
                for attachment_id_id in orphan_attachment_ids:
                    record.sudo().attachment_ids = [(4, attachment_id_id)]
