import os  
import subprocess  
import pymysql
import time
import requests
import urllib3
import traceback
from PIL import Image
from selenium import webdriver
from seleniumwire import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
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 anticaptchaofficial.imagecaptcha import *
from io import BytesIO
import base64
import sys 
inicio =sys.argv[1]
db = pymysql.connect("localhost","root","s9l8o7q6","estado",autocommit=True)
cursor = db.cursor()
cursor2 = db.cursor()
script="10"
dr="/usr/bin/chromedriver"
optionsx=Options()
optionsx.add_argument("--no-sandbox")
optionsx.add_argument("--headless")
optionsx.add_argument("--disable-dev-shm.usage")
driver = webdriver.Chrome(dr,options=optionsx)
#driver = webdriver.Chrome(dr)
i=0
while i<10000:
    try:
        sql = "SELECT * FROM `ruts_b1` where scan='' limit "+str(inicio)+",12"
        print(sql)
        user = ""
        pwd = ""
        chromedriver = "/usr/bin/geckodriver"
        cursor.execute(sql)
        results = cursor.fetchall()
#	print("ciclo "+str(i))
        for row in results:
            rut0=row[0]
            rut=rut0[0:-1]
            dv=rut0[-1:]
            rut1=int(int(rut)/1)
            fc2=row[2]
            print(rut)
            print(dv)
            print(rut1)
            rut3=str(rut1)+"-"+dv
            print(rut3)
            driver.get("https://portal.sidiv.registrocivil.cl/usuarios-portal/pages/DocumentRequestStatus.xhtml")
            time.sleep(7)
            #elements =driver.find_elements_by_xpath("//div[@class='texto']") //*[@id="form:run"]
            driver.find_element_by_id("form:run").send_keys(rut3)
            content=""
            error=""
    
   
            driver.save_screenshot('temp/screenshot_'+str(rut0)+'.png')
            im = Image.open('temp/screenshot_'+str(rut0)+'.png')
            img = driver.find_element_by_xpath('//*[@id="form:captchaPanel"]')
            loc = img.location
            left = loc['x']
            top = loc['y']
            right = loc['x'] + 290
            bottom = loc['y'] + 81
            im = im.crop((left, top, right, bottom)) # defines crop points form:inputCaptcha
            im.save('img/'+str(rut0)+'.png') # saves new cropped image
            
            
            with open("c_negro.png", "rb") as image_file:
                datan = base64.b64encode(image_file.read())
            with open("c_blanco.png", "rb") as image_file:
                datab = base64.b64encode(image_file.read())
            with open('img/'+str(rut0)+'.png', "rb") as image_file:
                datac = base64.b64encode(image_file.read())

            msg5="SI"
            if datan==datac:
                print("ES NEGRO===================================================================================")
                msg5="NO"
                
            if datab==datac:
                print("ES BLANCO===================================================================================")
                msg5="NO"
            if msg5=="SI":
                select = Select(driver.find_element_by_name('form:selectDocType'))
                select.select_by_index(1)
                #URL="http://localhost/estado/anti/examples/exampleimageToText.php?rut="+str(rut0)
                #sal=requests.get(URL)
                #print("SAL"+str(sal.content))
                #sali=str(sal.content)
                #sal1=sali.replace("b'","")
                #sal2=sal1.replace("'","")
                #salida=sal2
                #print(salida)
                #msg2=salida[0:3]
                #print(msg2)
                response=""
                solver = imagecaptcha()
                #solver.set_verbose(1)
                solver.set_key("d6cba4d6273b9432abd8633ef2c0c922")
                captcha_text = solver.solve_and_return_solution('img/'+str(rut0)+'.png')
                if captcha_text != 0:
                    print ("captcha text "+captcha_text)
                    response=captcha_text
                    msg2="OK:"
                else:
                    print ("task finished with error "+solver.error_code)
                    MSG="ER:"
                print(response)
                msg2="OK:"
                if captcha_text=="Captcha" or  captcha_text=="Black" or captcha_text == "Grey" or captcha_text=="ERROR_WRONG_FLAGS" or captcha_text=="White" or captcha_text=="error" or captcha_text=="EMPTY" or captcha_text=="ERROR_NO_SLOT_AVAILABLE":
                    msg3=35
                else:
                    msg3=4
                if msg2 == "OK:":
                    print("PERECTP")
                    #msg3=salida.replace("OK:","");
                    #driver.find_element_by_id("form:inputCaptcha").send_keys(msg3)
                    driver.find_element_by_id("form:inputCaptcha").send_keys(response)
                else:
                    print("MALITO")
                #volverTable setWidthOfSecondColumn confirmError
                driver.find_element_by_id("volverTable").click()
                time.sleep(2)
                content = driver.find_element_by_class_name('setWidthOfSecondColumn').text
                print(content)
                error=""
                if content=="":
                    time.sleep(1)
                    error=driver.find_element_by_id('confirmError').text
                    #os.remove('img/'+str(rut0)+'.png')
                    print("ERRor"+error)
                os.remove('temp/screenshot_'+str(rut0)+'.png')
                sql2="update ruts_b1 set scan='si',motivo='"+content+"',motivo2='"+error+"' where ruts='"+rut0+"'"
                print(sql2)
                error2=error.replace("\n"," ")
                error3=error2[0:35]
                URLx="http://206.189.238.123/estado/marcar.php?rut="+str(rut0)+"&motivo="+content+"&motivo2="+error2
                salx=requests.get(URLx)
                print(URLx)
                cursor.execute(sql2)
                time.sleep(msg3)
            i=i+1
            time.sleep(25)
    except Exception as e:
        print(e)
        traceback.print_exc()
        time.sleep(27)
