from __future__ import print_function
from odoo import models, fields, api,_
from odoo.exceptions import UserError, ValidationError,Warning
from psycopg2 import sql, DatabaseError
from pytz import timezone
from werkzeug import utils
import os.path
from datetime import datetime, timedelta
import json
import time
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from pprint import pprint
import logging

_logger = logging.getLogger(__name__)

SENDINBLUE_ACCOUNT_FILE = '/usr/lib/python3/dist-packages/odoo/kalachakra_module/kalachakra/static/sendinblue.json'

class MailingList(models.Model):
    _inherit = "mailing.list"
    _description = 'mailing list'

    id_sendinblue_list=fields.Integer('sendinblue list')
    
    #pas utilisée :
    def create_sendinblue_list(self):
            configuration = sib_api_v3_sdk.Configuration()
            f = open(SENDINBLUE_ACCOUNT_FILE)
            data = json.load(f)
            configuration.api_key['api-key'] = data['api_key']
            limit = 10
            offset = 0
            api_instance = sib_api_v3_sdk.ContactsApi(sib_api_v3_sdk.ApiClient(configuration))
            create_list = sib_api_v3_sdk.CreateList(name= 'Odoo '+self.name, folder_id=25)

            try:
                #api_response = api_instance.get_folders(limit, offset)
                #raise Warning(api_response)
                api_response = api_instance.create_list(create_list)
                #raise Warning(api_response)
                pprint(api_response)
                self.id_sendinblue_list=int(api_response.id)
            except ApiException as e:
                raise Warning("Exception when calling ContactsApi->create_list: %s\n" % e)

class MailingContact(models.Model):
    _inherit = "mailing.contact"
    _description = 'mailing contact'

    @api.model
    def create(self, values): 
       #_logger.error('create')
       #_logger.error(values)
    #    if not "list_ids" in values:
    #         mailing_list=self.env['mailing.list'].sudo().search([('name','=','Newsletter '+self.env.company.name)])
    #         if mailing_list:
    #             values['list_ids']=[(4,int(mailing_list.id))]
       res = super(MailingContact, self).create(values)
        #ajout du contact à la liste de diffusion de sendinblue
      
       res.create_sendinblue_contact()
       return res

    def write(self, values): 

       res = super(MailingContact, self).write(values)
        #ajout du contact à la liste de diffusion
    
       self.create_sendinblue_contact()
       return res

    def get_info_sendinblue_contact(self):
        #https://developers.sendinblue.com/reference/getfolders-1
        #_logger.error('get_info_sendinblue_contact')
        f = open(SENDINBLUE_ACCOUNT_FILE)
        data = json.load(f)
        configuration = sib_api_v3_sdk.Configuration()
        configuration.api_key['api-key'] = data['api_key']
        api_instance = sib_api_v3_sdk.ContactsApi(sib_api_v3_sdk.ApiClient(configuration))
        email = self.email
        
        try:
            #_logger.error('get_info_sendinblue_contact -1')
            api_response = api_instance.get_contact_info(email)
            
            
            return (api_response)
        except ApiException as e:
            #_logger.error('get_info_sendinblue_contact -2')
            #print("Exception when calling ContactsApi->get_contact_info: %s\n" % e)
            return False


    def create_sendinblue_contact(self):
            #_logger.error('create_sendinblue_contact')
            #_logger.error(str(self.email)+' '+ str(self.list_ids))
            if self.list_ids : 
                llist_ids=self.list_ids
            else:
                
                llist_ids=self.env['mailing.list'].sudo().search([('name','=','Newsletter '+self.env.company.name)])
                #llist_ids.append(mailing_list.id)

            if self.email and llist_ids:
                #_logger.error('create_sendinblue_contact -1')
                configuration = sib_api_v3_sdk.Configuration()
                #https://developers.sendinblue.com/reference/getfolders-1
                f = open(SENDINBLUE_ACCOUNT_FILE)
                data = json.load(f)
                configuration.api_key['api-key'] = data['api_key']
                limit = 10
                offset = 0
                api_instance = sib_api_v3_sdk.ContactsApi(sib_api_v3_sdk.ApiClient(configuration))
                list_ids=[]
                res=self.get_info_sendinblue_contact()
                #si le contact existe dans sendinblue, on lui rajoute la nouvelle
                # liste de diffusion
                if res:
                    #_logger.error('create_sendinblue_contact -2')
                    for id in llist_ids:
                        if id.id_sendinblue_list:
                            if not id.id_sendinblue_list in res.list_ids:
                                contact_emails = sib_api_v3_sdk.AddContactToList()
                                contact_emails.emails = [self.email]
                                try:
                                    api_response = api_instance.add_contact_to_list(id.id_sendinblue_list, contact_emails)
                                    pprint(api_response)
                                except ApiException as e:
                                    continue
                    return True
                #si le contact n'existe pas dans sendinblue, on le créé      
                else:
                    #_logger.error('create_sendinblue_contact -3')
                    for id in llist_ids:
                        list_ids.append(int(id.id_sendinblue_list))
                if list_ids!=[]:   
                    create_contact = sib_api_v3_sdk.CreateContact(email=self.email, list_ids=list_ids)

                    try:
                        #_logger.error('create_sendinblue_contact -4')
                        api_response = api_instance.create_contact(create_contact)
                        #raise Warning(api_response)
                        #_logger.error(api_response)
                        pprint(api_response)
                        return True
                        
                    except ApiException as e:
                        #_logger.error('create_sendinblue_contact -5')
                        #_logger.error(str(e))
                        #raise Warning("Exception when calling ContactsApi->create_list: %s\n" % e)
                        return False