import os  
import subprocess  
import pymysql
import time
import requests
import urllib3
import traceback
import sys
from PIL import Image
from webdriver_manager.chrome import ChromeDriverManager

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.options import Options
from captchatools import new_harvester
def existe(xpath):
    try:
        driver.find_element(By.XPATH,xpath)
    except NoSuchElementException:
        return False
    return True
def resuelve(val,rut0):
    if val==True:
        img = driver.find_element(By.XPATH,'/html/body/img[2]')
        loc = img.location
        left = loc['x']
        top = loc['y']
        right = loc['x'] + 310
        bottom = loc['y'] + 80
        #im = im.crop((left, top, right, bottom)) # defines crop points form:inputCaptcha
        #im.save('img/'+str(rut0)+'.png') # saves new cropped image
        sr=img.get_attribute("src")
        print("RUT"+str(rut0))
        print("SR "+str(sr))
            
            

            
        harvester = new_harvester(api_key="CAI-BA1D47513DC538310D4F34D07EE72C4F", solving_site="capsolver", captcha_type="image" )
        token = harvester.get_token(b64_img=str(sr))
        print(token)
        cmd='c:/curl/bin/curl.exe "http://206.189.238.123/def3/recibe.php" -H "Content-Type: application/x-www-form-urlencoded"  -X POST -d "img='+str(sr)+'&rut='+str(rut0)+'"'
        os.system(cmd)
        #print(cmd)
        time.sleep(6)
        url="http://206.189.238.123/def3/img/"+str(rut0)+".png"
        #url = "https://www.scienceabc.com/wp-content/uploads/ext-www.scienceabc.com/wp-content/uploads/2016/07/Captcha-ex.jpg-.jpg"
        msg2="OK:"
        driver.find_element(By.ID,"ans").send_keys(token)
        time.sleep(3)
        #volverTable setWidthOfSecondColumn confirmError formPrincipal msg-rojo
        driver.find_element(By.ID,"jar").click()
        time.sleep(2)
        content2=""                
    else:
        print("continua")
    
rut=sys.argv[1]
serie=sys.argv[2]
email=sys.argv[3]


driver = webdriver.Chrome()


driver.get("https://www.registrocivil.cl/OficinaInternet/web/carro.srcei")
time.sleep(5)
val=existe('/html/body/img[2]')
resuelve(val,rut)

#print(headers)
time.sleep(5)
#elements =driver.find_elements_by_xpath("//div[@class='texto']") //*[@id="form:run"]
val=existe('/html/body/img[2]')
#checkCert_133_1_2_false
#driver.find_element(By.ID,"checkCert_133_1_2_false").click()
time.sleep(5)
#driver.execute_script("document.getElementById('checkCert_133_1_2_false').click()")
#time.sleep(11)
driver.find_element(By.XPATH,"/html/body/div/div[9]/div[1]/div[2]/div[2]/table/tbody/tr[1]/td[1]/div").click()
time.sleep(6)
#driver.find_element(By.ID,"idInputRun_133_1_2").send
driver.execute_script("document.getElementById('idInputRun_133_1_2').value='"+str(rut)+"'")
time.sleep(5)
driver.execute_script("document.getElementById('btn_agregarCarro_1#133_1_2#99').click()")
val=existe('/html/body/img[2]')
resuelve(val,rut)
time.sleep(6)
#carro_solicitanteInputRunSolicitante
driver.execute_script("document.getElementById('carro_solicitanteInputRunSolicitante').value='"+str(rut)+"'")
time.sleep(2)
driver.execute_script("document.getElementById('carro_solicitanteInputNDocSolicitante').value='"+str(serie)+"'")
time.sleep(2)
driver.execute_script("document.getElementById('carro_solicitanteInputEmail').value='"+str(email)+"'")
time.sleep(2)
driver.execute_script("document.getElementById('carro_solicitanteInputEmailConfirm').value='"+str(email)+"'")
time.sleep(4)
#driver.execute_script("document.getElementById('carro_btnContinuar').click()")
time.sleep(25)