from flask import current_app
from datetime import datetime, timedelta
import time
import random
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.chrome.options import Options

from msedge.selenium_tools import EdgeOptions
from msedge.selenium_tools import Edge

from selenium.webdriver.chrome.webdriver import DesiredCapabilities
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.remote.webelement import WebElement
import seleniumwire.undetected_chromedriver.v2
from dao.Conn import ConnMySql
from vo.ProxyInfo import ProxyInfo

# 等待元素出现，timeout-等待时长，frequency等待期间检查频率，均为秒
def waitElement(browser: WebDriver, by: str, selecter: str, timeout: int = 20, frequency: int = 1) -> WebElement:
    ret = None
    t1 = datetime.now()
    while (datetime.now() - t1).seconds < timeout:
        if hasElement(browser, by, selecter):
            ret = getElement(browser, by, selecter)
            break
        time.sleep(frequency)
    return ret


# 获取元素，无则返回None
def getElement(browser: WebDriver, by: str, selecter: str) -> WebElement:
    ret = None
    try:
        ret = browser.find_element(by, selecter)
    except:
        pass
    return ret

# 判断元素是否存在。
def hasElement(browser: WebDriver, by: str, selecter: str) -> bool:
    ret = True
    try:
        browser.find_element(by, selecter)
    except:
        ret = False
    return ret


# 返回页面元素指定属性的值，如class，若未找到元素，则返回空串
def getAttr(brow: webdriver, by: str, selector: str, attr: str) -> str:
    ret = ""
    try:
        s = brow.find_element(str, selector).get_attribute(attr)  #
    except:
        pass
    return ret


# 打开Edge浏览器
def newEdge(useProxy):
    edge_options = EdgeOptions()
    edge_options.use_chromium = True
    edge_options.add_argument('--disable-blink-features=AutomationControlled')
    driver = webdriver.Edge(options=edge_options)
    # driver.get('https://bing.com')
    # element = driver.find_element(By.ID, 'sb_form_q')
    # element.send_keys('WebDriver')
    # element.submit()
    return driver


# 打开Chrome浏览器
# url：浏览器启动时需要打开的url
# useProxy：使用使用代理，True-使用
# cookie：需要设置的cookie信息，如登录信息。
def newChrome(url: str = "", debugMode: bool = False, useProxy: bool = False, cookie: str = "") -> WebDriver:
    # 禁止浏览器自动关闭
    option = webdriver.ChromeOptions()
    if debugMode == False:
        option.add_experimental_option("detach", True)
        option.add_experimental_option('excludeSwitches',['enable-automation'])  # 去掉web自动化，window.navigator.webdriver=undefined
        option.add_experimental_option('useAutomationExtension', False)  # 取消chrome受自动控制提示
    option.add_argument("--disable-blink-features=AutomationControlled")
    option.add_argument('disable-infobars')  # 不显示Chrome正在受自动软件控制
    option.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
    option.add_argument('--ignore-certificate-errors')
    # option.add_argument("--user-data-dir=C:/Users/Administrator/AppData/Local/Google/Chrome/User Data/Default");
    # option.add_argument("--test-type=allow-running-insecure-content");
    # option.add_argument('--headless')  # 后台运行Chrome

    # 随机设置代理IP，分为http代理和socks5代理。useProxy=False时，需要清除原来设置的代理
    isHttpProxy = False
    seleniumwire_options = {}
    proxy = None
    if useProxy:
        # 读取一个IP代理，如果已经到最后一个，则重新从0开始
        conn = ConnMySql()
        proxyInfo: ProxyInfo
        proxyInfo = conn.proxyGetNext(current_app.config['sys.proxyid'])
        print("proxy_id："+str(current_app.config['sys.proxyid'])+"，"+proxyInfo.ip,flush=True)
        if proxyInfo is None:
            current_app.config['sys.proxyid'] = 0
            proxyInfo = conn.proxyGetNext(current_app.config['sys.proxyid'])
        current_app.config['sys.proxyid'] = proxyInfo.id
        desired_capabilities = webdriver.DesiredCapabilities.CHROME.copy()
        sProxy = ""
        if proxyInfo.user_name == "":
            # option.add_argument(f'--proxy-server=http://{proxy_ip}:{proxy_port}')
            # sProxy = f'--proxy-server=http://{proxy_ip}:{proxy_port}'
            sProxy = f'http://{proxyInfo.ip}:{proxyInfo.port}'
        else:
            # option.add_argument(f'--proxy-server=http://{proxy_username}:{proxy_password}@{proxy_ip}:{proxy_port}')
            # sProxy = f'--proxy-server=http://{proxy_username}:{proxy_password}@{proxy_ip}:{proxy_port}'
            sProxy = f'http://{proxyInfo.user_name}:{proxyInfo.user_passwd}@{proxyInfo.ip}:{proxyInfo.port}'
        webdriver.DesiredCapabilities.CHROME['proxy'] = {
            "httpProxy": sProxy,
            "sslProxy": sProxy,
            "proxyType": "manual"
        }
        conn.close()
    # 随机设置UserAgent
    userAgent = getUserAgent()
    # option.add_argument('user-agent=%s' %userAgent)


    if url != "":
        option.add_argument('--app ' + url)  # 在默认窗口打开链接 https://wenshu.court.gov.cn

    if debugMode:
        #option.debugger_address = "127.0.0.1:9222"
        option.add_experimental_option('debuggerAddress', '127.0.0.1:9222')
    # 创建 Chrome 浏览器实例，同时设置代理信息
    driver = webdriver.Chrome(
        options=option)  # service=ChromeService(ChromeDriverManager().install()), chrome_options  options=option , desired_capabilities=desired_capabilities, seleniumwire_options=seleniumwire_options

    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
            Object.defineProperty(navigator, 'webdriver', {
              get: () => undefined
            })
          """
    })
    if debugMode == False:
        driver.maximize_window()  # 窗口最大化
    driver.delete_all_cookies()  # 清除cookies
    # cookie后续改为bool型，=True则每次从数据库中读取一个保存的cookie登录，登录后可能需要保存cookie，因为过期时间可能被重新设置。
    # 需要时也可由专门的后台任务定期对最近未登录的cookie进行重新登录并保存新的cookie
    if cookie != "":
        cookie_dict = eval(cookie)
        driver.add_cookie(cookie_dict)
        driver.refresh()
    return driver


# 返回代理IP及端口号，例：1.2.3.4:555
def getProxyIP():
    return ""


# 随机返回一个浏览器的UserAgent
def getUserAgent():
    user_agents = [
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
        "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
        "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
        "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
        "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
        "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
        "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
        "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
        "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
        "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
        "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
        "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
        "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
        "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10"
    ]
    # random.choice返回列表的随机项
    user_agent = random.choice(user_agents)
    return user_agent
