# -*- coding: utf-8 -*-

from logging import getLogger

from odoo import api, models, fields

from odoo.exceptions import UserError

_logger = getLogger(__name__)


class SgtPortalWizard(models.TransientModel):
    _inherit = 'portal.wizard'

    @api.onchange('portal_id')
    def onchange_portal_id(self):
        """Sobreescribiendo la función original para que por default el boolean in_portal
        esté True cuando el registro sea una compañia"""
        # for each partner, determine corresponding portal.wizard.user records
        partner_ids = self.env.context.get('active_ids', [])
        contact_ids = set()
        user_changes = []
        for partner in self.env['res.partner'].sudo().browse(partner_ids):
            contact_partners = partner.child_ids or [partner]
            for contact in contact_partners:
                # make sure that each contact appears at most once in the list
                if contact.id not in contact_ids:
                    contact_ids.add(contact.id)
                    if contact.is_contribuyente and contact.analista_verificacion_ids:
                        in_portal = True
                    else:
                        in_portal = False
                    if contact.user_ids:
                        in_portal = self.portal_id in contact.user_ids[0].groups_id
                    user_changes.append((0, 0, {
                        'partner_id': contact.id,
                        'email': contact.email,
                        'in_portal': in_portal,
                    }))
        self.user_ids = user_changes

    @api.multi
    def action_apply(self):
        _logger.info('\n\n\n {} \n\n\n'.format(self.user_ids))
        for i in self.user_ids:
            _logger.info('\n\n\n {} \n\n\n'.format(i))
            cuenta = self.env['sgt_cuentas'].search([('partner_id', '=', i.partner_id.id)])
            if not cuenta and i.partner_id.analista_verificacion_ids:
                self.ensure_one()
                self.env['sgt_cuentas'].create({'partner_id': i.partner_id.id,
                                                'state': 'activo',
                                                'ciclo_facturacion_id': 1})
                i.action_apply()
                _logger.info('\n\n\n {} \n\n\n'.format(i))
            else:
                return
        return {'type': 'ir.actions.act_window_close'}

class WizardUser(models.TransientModel):
    _inherit = 'portal.wizard.user'

    @api.multi
    def _send_email(self):
        if not self.env.user.email:
            raise UserError(('Debe tener una dirección de correo electrónico en sus Preferencias de usuario para enviar correos electrónicos.'))

        # determine subject and body in the portal user's language
        template = self.env.ref('kyb_sgt_acceso_portal.mail_template_welcome_sgt')
        for wizard_line in self:
            lang = wizard_line.user_id.lang
            partner = wizard_line.user_id.partner_id

            portal_url = partner.with_context(signup_force_type_in_url='', lang=lang)._get_signup_url_for_action()[partner.id]
            partner.signup_prepare()

            if template:
                template.with_context(dbname=self._cr.dbname, portal_url=portal_url, lang=lang).send_mail(wizard_line.id, force_send=True)
            else:
                _logger.warning("No se encontró una plantilla de correo electrónico para enviar correos electrónicos al usuario del portal")

        return True