from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError, Warning
from psycopg2 import sql, DatabaseError
from odoo.tools.safe_eval import safe_eval
from datetime import date, datetime, time,timedelta
from dateutil.relativedelta import relativedelta
from odoo import fields, http, SUPERUSER_ID, tools, _
from werkzeug import utils
import csv
import base64
import io
import json
import re       
                    
    

class membershipimport(models.Model):
    _name = 'kalachakra.membershipimport'
    _description = 'import memberships from csv'
    
       

    def import_membership_csv_files(self):
        
        files= self.env["opendons.partnerdraftfile"].search([('source_name','=','membership')])
       
        for f in files:
            
            decrypted = base64.b64decode(f.file).decode('utf-8-sig')
            source_name=f.source_name
            membership_product=self.env['product.product'].sudo().search([('membership_product','=',True)],limit=1)

            with io.StringIO(decrypted) as fp:
                reader = csv.DictReader(fp, delimiter=",", quotechar='"')
                for row in reader:
                    vals={}
                    vals['partner_id']=False
                    vals['product_id']=membership_product.id
                    vals['start_date']=False
                    vals['state']='done'
                    vals['payment_state']='paid'
                    type_rec=''
                    for key, value in row.items():
                        #on cherche le contact
                        
                        
                        if key=='id_contact':
                         partner=self.env['res.partner'].search([('external_id','=',value)])
                         if partner:
                            vals['partner_id']=partner.id
                        if key=='type':
                            type_rec=value
                        if key=='debut_adhesion':
                            if value!='0000-00-00':
                                year_m=value[0:4]
                                month_m=value[5:7]
                                day_m=value[8:10]
                                if year_m=='2021':
                                    start_date=datetime.strptime(year_m+'-'+month_m+'-'+day_m, '%Y-%m-%d')
                                    ref_date=datetime.strptime('2021-08-15', '%Y-%m-%d')
                                    
                                    if start_date>=ref_date:
                                        vals['start_date']=start_date
                                        vals['end_date']=start_date+relativedelta(years=1)
                        # field_map=self.env['opendons.partnerdraftfile_mapping'].search([('external_field','=',key)])
                        # if field_map:
                        #     odoo_field=field_map.odoo_field
                        #     vals[odoo_field]=str(value)
                            
                        # else: raise Warning('champ '+str(key)+' non trouvé')
                    
                    if vals['partner_id'] and vals['start_date']:
                        self.env['kalachakra.membership'].create(vals)

                   
        return True

    def import_membership_csv_files_v2(self):
        
        files= self.env["opendons.partnerdraftfile"].search([('source_name','=','membership')])
       
        for f in files:
            
            decrypted = base64.b64decode(f.file).decode('utf-8-sig')
            source_name=f.source_name
            membership_product=self.env['product.product'].sudo().search([('membership_product','=',True)],limit=1)

            with io.StringIO(decrypted) as fp:
                reader = csv.DictReader(fp, delimiter=";", quotechar='"')
                for row in reader:
                    vals={}
                    vals['partner_id']=False
                    vals['product_id']=membership_product.id
                    vals['start_date']=False
                    vals['state']='done'
                    vals['payment_state']='paid'
                    type_rec=''
                    for key, value in row.items():
                        #on cherche le contact
                        
                        
                        if key=='id':
                         partner=self.env['res.partner'].search([('external_id','=',value)])
                         if partner:
                            vals['partner_id']=partner.id

                        
                        if key=='Date adhesion':
                                year_m=value[12:16]
                                month_m=value[17:19]
                                day_m=value[20:22]
                                start_date=datetime.strptime(year_m+'-'+month_m+'-'+day_m, '%Y-%m-%d')
                                vals['start_date']=start_date
                                vals['end_date']=start_date+relativedelta(years=1)
                        
                    
                    if vals['partner_id'] and vals['start_date']:
                        
                        self.env['kalachakra.membership'].create(vals)

                   
        return True

    def update_super_member(self):

        partner=self.env['res.partner'].search([])
        for p in partner:
            
            if p.statut_contact=='soutien':
                
                p.super_member=True