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, datetime

from werkzeug import utils
import csv
import base64
import io
import json        
                    
    

class kalachakra_partnerdraftfile(models.Model):
    _name = 'kalachakra.partnerdraftfile'
    _description = 'draft partner file'
    
    #file= fields.Binary("Téléverser le fichier des contacts")
    file = fields.Binary("Attachment")
    file_name = fields.Char("Nom du fichier")
    active = fields.Boolean("actif")
    source_name=fields.Char("Source")

    def import_csv_files(self):
        self.env["kalachakra.partnerdraft"].search([]).unlink()
        files= self.env["kalachakra.partnerdraftfile"].search([('active','=',True)])
        #raise Warning('fff')
        for f in files:
            decrypted = base64.b64decode(f.file).decode('utf-8-sig')
            source_name=f.source_name
            with io.StringIO(decrypted) as fp:
                reader = csv.DictReader(fp, delimiter=";", quotechar='"')
                for row in reader:
                    vals={}
                    vals['source_name']=source_name
                    for key, value in row.items():
                        
                        field_map=self.env['kalachakra.partnerdraftfile_mapping'].search([('external_field','=',key)])
                        if field_map:
                            odoo_field=field_map.odoo_field
                            vals[odoo_field]=str(value)
                            
                        else: raise Warning('champ '+key+' non trouvé')
                    self.env['kalachakra.partnerdraft'].create(vals)

                    #raise Warning(json.dumps(row))
        action = self.env.ref("kalachakra.kalachakra_partnerdraft_action").sudo().read([])[0]
                
        return action

    def transfert_draftpartner(self):
        #transfert des contacts importés, dans la base des contact odoo
        partners=self.env['kalachakra.partnerdraft'].search([])
        
        if partners:
            for p in partners:
                vals={}
                vals['name']=p.name
                vals['company_type']='person'
                vals['firstname']=p.firstname
                
                vals['source']=p.source_name
                vals['street']=p.street
                vals['street2']=p.street2
                vals['city']=p.city
                vals['zip']=p.zip
                vals['phone']=p.phone
                vals['email']=p.email
                vals['statut_contact']=p.statut_contact.lower()
                vals['date_creation_contact']=p.date_creation_contact
                vals['origine']=p.origine.lower()
                vals['date_adhesion']=p.date_member
                
                


                if p.country!='':
                    country=self.env['res.country'].search([('name','=',p.name)])
                    if country:vals['country_id']=country.id
                    else:vals['country_id']=False
                else:
                    vals['country_id']=False

                if p.title!='':
                    title=self.env['res.partner.title'].search([('name','=',p.title)])
                    if title:vals['title']=title.id
                    else:vals['title']=False
                else:
                    vals['title']=False


                self.env['res.partner'].create(vals)
        partners=self.env['kalachakra.partnerdraft'].search([]).unlink()
                

   


class kalachakra_partnerdraftfile_mapping(models.Model):
    _name = 'kalachakra.partnerdraftfile_mapping'
    _description = 'file mapping'
    

    external_field=fields.Char('external field')
    odoo_field=fields.Selection('odoo_field_selection', string='odoo field')

    @api.model
    def odoo_field_selection(self):
        field_list=self.env['kalachakra.partnerdraft'].fields_get()
        
        result=[]
        for key in field_list:
             result.append((key,key))
        result.sort()
        return result
class kalachakra_partnerdraft(models.Model):
    _name = 'kalachakra.partnerdraft'
    _description = 'import draft partner'
    _order = "id asc"
    
    # external_id=fields.Char(string='external id')
    # name=fields.Char(string='nom')
    # firstname=fields.Char(string='prenom')
    # title=fields.Char(string='civilité')
    # street = fields.Char(string='adresse')
    # street2 = fields.Char(string='adresse2')
    # city = fields.Char(string='ville')
    # country = fields.Char(string='pays')
    # zip = fields.Char(string='code postal')
    # phone = fields.Char(string='tel')
    # email = fields.Char(string='Email')
    # statut_contact=fields.Char('Statut')
    # date_creation_contact=fields.Char(string='Date contact')
    # origine=fields.Char(string='Origine')
    # date_member=fields.Char(string='Date adhesion')
    # doublon=fields.Boolean(string='Doublon')
    # source_name=fields.Char(string='Source')
