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


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'),
                    ],'Origine',  index=True)
    
    date_adhesion=fields.Char(string='Date adhesion', readonly=True)
    def  _compute_end_date_membership(self):

        for rec in self:
            rec.date_membership=False
            partner_mb=self.env['kalachakra.membership'].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.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
        return res
    
    def unlink(self):
        # suppression du compte utilisateur lié au contact
        self.env['res.users'].sudo().search([('partner_id','=',int(self.id))]).unlink()
        return super(ResPartner, self).unlink()
    
    @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')
    
    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))]})

