from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError, Warning
from psycopg2 import sql, DatabaseError
from datetime import datetime
from werkzeug import utils
import re
import logging
_logger = logging.getLogger(__name__)


class ResPartner(models.Model):
    _inherit = 'res.partner'
    external_id=fields.Char('id')
    statut_contact=fields.Selection([('adherent', 'Adhérent'), ('bienfaiteur', 'Bienfaiteur'),('contact', 'Contact'), ('soutien','Soutien') ],'Statut', index=True)
    date_creation_contact=fields.Char(string='Date de création du contact', readonly=True)
    origine=fields.Selection([
       ('boutique','Boutique'),
            ('visiteur','Visiteur'),
            ('vincennes','Vincennes'),
            ('bercy','Bercy'),
            ('salon zen','Salon Zen'),
            ('autre','Autre'),
            ('internet boutique','Internet Boutique'),
            ('conf M ricard','Conf M Ricard'),
            ('visite lzr 09','Visite lzr 09'),
            ('retraite','Retraite'),
            ('amis','Amis'),
            ('centre FPMT','Centre FPMT'),
            ('site réservations','Site réservations'),
            ('réservations','Réservations'),
            ('voyage inde','Voyage inde'),
            ('internet','Internet'),
            ('librairie','Librairie'),
            ('site internet boutique','Site internet boutique'),
            ('portes ouvertes st cosme','Portes ouvertes st cosme'),
            ('t','T'),
            ('maitreya','maitreya'),
            ('zen','Zen'),
            ('Lille','Lille'),
            ('alan wallace','Alan wallace'),
            ('salon Rouen','Salon Rouen'),
            ('stage','Stage'),
            ('b.Actualit','B.Actualit'),
            ('b. Actualit','B. Actualit'),
            ('r','R'),
            ('institut vy','Institut vy'),
            ('initiation kalachakr','Initiation kalachakr'),
            ('yoga','Yoga'),
            ('samsara','Samsara'),
            ('missun@gmail.com','missun@gmail.com'),
            ('reliques','Reliques'),
            ('journal m','Journal m'),
            ('nantes','Nantes'),
            ('retraite vipassana','retraite vipassana'),
            ('presse bouddhiste','Presse bouddhiste'),
            ('réservtions','Réservtions'),
            ('réservation','Réservation'),
            ('site','Site'),
            ('question mail','Question mail'),
            ('interreligieux','interreligieux'),
            ('refuge','Refuge'),
            ('zoom','zoom'),
            ('import_don2022','Import dons 2022'),
                    ],'Origine',  index=True)
    
    date_adhesion=fields.Char(string='Date adhesion', readonly=True)
    birthday_date=fields.Date(string="Birthday date")
    birthday_year=fields.Integer(string="Birthday year")
    contact_form_update_date=fields.Date(string="contact form update date")
    
    name_for_list = fields.Char('name', compute='_compute_name_for_list',store=True)
    def  _compute_end_date_membership(self):

        for rec in self:
            rec.date_membership=False
            partner_mb=self.env['kalachakra.membership'].sudo().search([('partner_id','=',int(rec.id))],order="end_date desc",limit=1)
            if partner_mb:
                rec.date_membership=partner_mb.end_date

    date_membership=fields.Date(string='membership end date', compute='_compute_end_date_membership')
    @api.depends('super_member')
    def  _compute_member_status(self):
        for rec in self:
            
            member=rec.env['kalachakra.membership'].search([('partner_id','=',rec.id),('end_date','>=',datetime.now()),('payment_state','=','paid')])
            if member : rec.member_status='member'
            else :rec.member_status='not member'
            if rec.super_member: rec.member_status='super member'

    member_status=fields.Selection(string='member status',selection=[('not member','Not member'),('member','Member'),('super member','Super member')] 
    ,compute="_compute_member_status",store=True,default='not member')
    
    super_member=fields.Boolean("Super member")
    has_user_account=fields.Boolean("has user account", compute="_compute_has_user_account")
    
    def _compute_has_user_account(self):
        for rec in self:
            rec.has_user_account=False
            user=self.env['res.users'].search([('partner_id','=',int(rec.id))])
            if user: rec.has_user_account=True

    @api.onchange('super_member')
    def onchange_super_member(self):
        
        self._compute_member_status()
    
    @api.constrains('phone')
    def _onchange_phone(self):
        pass
    
    @api.constrains('mobile')
    def _onchange_mobile(self):
        pass
    @api.model
    def create(self, values):
        res = super(ResPartner, self).create(values)
        country_france=self.env['res.country'].sudo().search([('name','=','France')])
        if not res.country_id:res.country_id=country_france.id
        #ajout du contact à la mailing liste principale
        if res.email:
            mailing_contact=self.env['mailing.contact'].sudo().search([('email','=',res.email)],limit=1)
            

            mailing_list=self.env['mailing.list'].sudo().search([('name','=','Newsletter '+self.env.company.name)])
            if mailing_list:
                if not mailing_contact:
                    vals={}
                    vals['email']=res.email
                    vals['name']=res.name
                    vals['title_id']=int(res.title)
                    vals['country_id']=int(res.country_id)
                    vals['list_ids']=[(4,int(mailing_list.id))]
                    mailing_contact=self.env['mailing.contact'].sudo().create(vals)
                else:
                    if not mailing_list in mailing_contact.list_ids:
                        mailing_contact.sudo().write({'list_ids':[(4,int(mailing_list.id))]})

        return res
    
    def unlink(self):
        # suppression du compte utilisateur lié au contact
        for rec in self:
            self.env['res.users'].sudo().search([('partner_id','=',int(rec.id))]).unlink()
            super(ResPartner, rec).unlink()
        return 
    
    @api.constrains('email')
    def _onchange_email(self):
        if self.email:
            if not self.image_1920 and self._context.get('gravatar_image') and self.email:
                self.image_1920 = self._get_gravatar_image(self.email)
            regex = re.compile(r'([A-Za-z0-9-]+[.-_])*[A-Za-z0-9-]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')
            if not re.fullmatch(regex, self.email):
               
                raise ValidationError('Invalid email')
    
    @api.onchange('zip')
    def _onchange_zip(self):
        pass

    def add_partners_to_main_sb_list(self):

        mailing_list=self.env['mailing.list'].sudo().search([('name','=','Newsletter '+self.env.company.name)])
        #partner created after 20/08/2022
        partner=self.env['res.partner'].search([('email','!=',False),('create_date','>','2022-08-20')])
        for p in partner:

            mailing_contact=self.env['mailing.contact'].sudo().search([('email','=',p.email)],limit=1)
            if not mailing_contact:
                    vals={}
                    vals['email']=p.email
                    vals['name']=p.name
                    vals['title_id']=int(p.title)
                    vals['country_id']=int(p.country_id)
                    vals['list_ids']=[(4,int(mailing_list.id))]
                    mailing_contact=self.env['mailing.contact'].sudo().create(vals)
                    _logger.error("created and added to main sb list:"+str(p.email))
            else:
                    if not mailing_list in mailing_contact.list_ids:
                        mailing_contact.write({'list_ids':[(4,int(mailing_list.id))]})
                        _logger.error("updated and added to main sb list:"+str(p.email))

    def partners_near_saint_cosme(self):
        
        mailing_list=self.env['mailing.list'].sudo().search([('name','=','Habitants départements 28, 61, 72')])

        partner=self.env['res.partner'].search(['|','|',('zip','=like','28%'),('zip','=like','61%'),('zip','=like','72%')])
        for p in partner:

            mailing_contact=self.env['mailing.contact'].sudo().search([('email','=',p.email)],limit=1)
            #si le contact n'existe pas comme mailing contact, création
            if not mailing_contact:
                vals={}
                vals['email']=p.email
                vals['name']=p.name
                vals['title_id']=int(p.title)
                vals['country_id']=int(p.country_id)
                vals['list_ids']=[(4,int(mailing_list.id))]
                mailing_contact=self.env['mailing.contact'].sudo().create(vals)
            else:
                #si le contact existe, si la liste de diffusion n'est pas lié au contact, on l'ajoute
                if not mailing_list in mailing_contact.list_ids:
                    mailing_contact.sudo().write({'list_ids':[(4,int(mailing_list.id))]})

    @api.depends('name')
    def _compute_name_for_list(self):
        for rec in self:
            rec.name_for_list=rec.name

    @api.depends('name','donor_id')
    def name_get(self):
        res = []
        for record in self:
            if not record.is_company:
                donor = record.donor_id + " " if record.donor_id else ""
            else:
                donor=''
            name_ = record.name + " " if record.name else ""
            first_name_ = record.firstname if record.firstname else ""
            name = donor + name_ + first_name_
            res.append((record.id,name))
        return res
    
    def _update_email_to_lower(self):
        
            users = self.env['res.users'].search([])
            for u in users:
                _logger.info(u.login)
                try:
                    u.login=u.login.lower()
                    _logger.info(u.login)
                except :
                    _logger.info('erreur :'+u.login)