#!/usr/bin/python

import json
import time
import pymysql.cursors
import pymysql
import clearbit
from datetime import datetime
from couchbase.cluster import Cluster, ClusterOptions
from couchbase_core.cluster import PasswordAuthenticator

cluster = Cluster('couchbase://docs.gigminds.com', ClusterOptions(PasswordAuthenticator('admin', 'Tanya@12')))
cb = cluster.bucket('default')
cb_coll = cb.default_collection()

clearbit.key = 'sk_e97ec00d29e799f92d7fa7b33118b4c2'

db = pymysql.connect (host="cldy-hub-db-prod-do-user-1524670-0.a.db.ondigitalocean.com",
                     user="doadmin",
                     passwd="jmbly6e4obtma5z0",
                     db="defaultdb",
                     port=25060,
                     charset='utf8mb4',
                     cursorclass=pymysql.cursors.DictCursor)

with db.cursor() as cursor:
    #sql = "SELECT `email` FROM `person` where `email` is not null and `type` = 'Hiring Manager' order by `created_at` desc limit 100;"
    sql = "select id, uuid, first_name, last_name, email, organization, created_at from person where created_at > curdate() - 1 order by created_at desc;"
    cursor.execute(sql)
    records = cursor.fetchall()

    for record in records:
        rv = cb_coll.get(record['email'], quiet=True)
        if rv.success:
            print(record['email'], ' - existing')
        else:
            print (record['email'], " - Item not found")

            try:
                response = clearbit.Enrichment.find(email=record['email'], stream=True)
            

                if response['person'] is not None:
                    person = response['person']
                    person['type'] = 'person'                    
                    person['id'] = record['email'].lower()
                    person['created_at'] = time.ctime()
                    person['uuid'] = record['uuid']
                    person['db_id'] = record['id']

                    cb_coll.upsert(person['id'], person)

                if response['company'] is not None:
                    company = response['company']
                    company['type'] = 'company'
                    company['id'] = company['domain'].lower()
                    company['created_at'] = time.ctime()

                    cb_coll.upsert(company['id'], company)    
            except:
                print ("Skipping", ' -', record['email'])

            #print(response['person'])

        
        

