
import time
import traceback

from loguru import logger
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

from ocr import DdddOcr

# code by wlt233 | for LoveLive! Series AsiaTour 2024
# 2024.11.10 | v0.1
# ref: https://www.ticketlink.co.kr/global/zh/product/51390



def get_cookie(username, password, headless):
    try:
        ocr = DdddOcr(origin_onnx_path="./data/common_old.onnx", show_ad=False)
        ocr.set_ranges(2)
        
        options = Options()
        options.headless = headless
        driver = webdriver.Chrome(chrome_options=options,
                                  executable_path="./data/chromedriver.exe")
        driver.get("https://www.ticketlink.co.kr/global/zh/product/51390")
        driver.find_element(by=By.ID,value="loginBtn").click()
        time.sleep(3)

        driver.switch_to.window(driver.window_handles[-1])
        driver.find_element(by=By.ID,value="id").send_keys(username)
        driver.find_element(by=By.ID,value="pw").send_keys(password)
        driver.find_element(by=By.ID,value="loginBtn").click()
        time.sleep(3)

        driver.switch_to.window(driver.window_handles[-1])
        driver.get("https://www.ticketlink.co.kr/global/zh/reserve/plan/schedule/1740993756")
        
        driver.find_element(by=By.ID,value="captcha_img").screenshot("./data/captcha.jpg")
        with open("./data/captcha.jpg", "rb") as f:
            img = f.read()
        result = str(ocr.classification(img)).upper()
        logger.info(f"验证码：{result}")
        driver.find_element(by=By.ID,value="ipt_captcha").send_keys(result)
        driver.find_element(by=By.CLASS_NAME,value="btn_submit").click()
        time.sleep(1)
        error_cls = driver.execute_script("return document.getElementsByClassName('txt_error')[0].getAttribute('class');")
        while not "ng-hide" in error_cls:
            driver.execute_script("document.getElementsByClassName('btn_refresh')[2].click();")
            time.sleep(1)
            driver.find_element(by=By.ID,value="captcha_img").screenshot("./data/captcha.jpg")
            with open("./data/captcha.jpg", "rb") as f:
                img = f.read()
            result = str(ocr.classification(img)).upper()
            logger.info(f"验证码：{result}")
            driver.find_element(by=By.ID,value="ipt_captcha").send_keys(result)
            driver.find_element(by=By.CLASS_NAME,value="btn_submit").click()
            time.sleep(1)
            error_cls = driver.execute_script("return document.getElementsByClassName('txt_error')[0].getAttribute('class');")
        
        cookies = driver.execute_script("return document.cookie;")
        return cookies
    except Exception as e:
        logger.error(f"{e} {e.args}\n{traceback.format_exc()}")
        return ""



if __name__ == "__main__":
    get_cookie("vj.zhzh.dbb.d.udhj.db@gmail.com", "Nijigasaki27", False)