import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import csv
import hashlib
import time
import psycopg2

conn = psycopg2.connect(database="db_crm",
                        user="finix",
                        host='localhost',
                        password="Ay0ubAdmIn",
                        port=5432)
cursor = conn.cursor()
cursor.execute("SELECT * from public.logfile where fichier like '%traitement_cda.py%';")
result = cursor.fetchone()

if result == None:
    chrome_options = Options()
    chrome_options.add_argument("--disable-extensions")
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--no-sandbox")  # linux only
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--start-maximized")

    driver = webdriver.Chrome(options=chrome_options)
    # driver = webdriver.Chrome()
    driver.maximize_window()
    wait = WebDriverWait(driver, 10)
    driver.get("https://crmcallcda.com/index.php")

    driver.find_element("id", "username").send_keys("fabien")
    # find password input field and insert password as well
    driver.find_element("name", "thepass").send_keys("fabien")
    # click login button
    driver.find_element("css selector", ".btn-primary").click()
    print(driver.current_url)

    cursor2 = conn.cursor()
    cursor2.execute("SELECT contrat from public.leads where iban IS NULL and source = 'CDA' order by id_lead asc;")
    resultsLeads = cursor2.fetchall()

    for row in resultsLeads:
        datas = []
        contrat = row[0].strip()
        id_fiche = contrat[4:]
        hash = hashlib.md5(id_fiche.encode("utf-8")).hexdigest()
        try:
            cursor4 = conn.cursor()
            cursor4.execute("SELECT contrat from public.leads where email IS NOT NULL and contrat = '"+contrat+"' ;")
            resultExiste = cursor4.fetchone()

            if resultExiste == None:
                new_url = "https://crmcallcda.com/editcontrat.php?hash=" + hash
                driver.execute_script("window.open('');")
                driver.switch_to.window(driver.window_handles[1])
                driver.get(new_url)
                print(new_url)
                emailT = driver.find_element(By.XPATH, "//input[contains(@id, 'email')]")
                email = emailT.get_attribute('value')
                ibanT = driver.find_element(By.XPATH, "//input[contains(@id, 'iban')]")
                iban = ibanT.get_attribute('value')

                record_to_update = (email, iban, contrat)
                cursor3 = conn.cursor()
                postgres_update_query = """ UPDATE leads SET email = %s,iban = %s WHERE contrat = %s """
                cursor3.execute(postgres_update_query, record_to_update)
                conn.commit()
                count = cursor3.rowcount
                print("CONTRAT : ",contrat)
                print("HASH : ",hash)
                print("EMAIL : ",email)
                print("IBAN : ",iban)
                print(count, "Modification a été faite avec succès !!")
        except:
          print("CONTRAT NON TROUVE !!!")