# -*- coding:utf-8 -*-
from selenium import webdriver
from engine.read_config import ReadConfig
import time, os, re


class BrowserEngine(ReadConfig):
    __log_name = "browser_engine"

    def __init__(self, image_path, log_name=__log_name, url='URL'):
        super().__init__(log_name)
        # self.__logger = super().get_logger()
        self._log_name = log_name
        self._browser = ''
        self.url = url
        self._driver_path = r"C:\Users\80980\znfz_autotest\driver\chromedriver.exe"
        self.image_path = image_path

        self.driver = webdriver.Chrome(self._driver_path)
        self.open_browser()
        self.login_znfz()
        self.get_page()
        self.driver.xpath = self.driver.find_elements_by_xpath

    def open_browser(self):
        browser = self.get_browserType('browserName')
        url = self.get_testUrl('URL')
        self.logger.info("browserName: %s" % browser)

        # driver = webdriver.Chrome(r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe")

        self.driver.get(url)
        self.logger.info("Open url: %s" % url)
        time.sleep(1)
        self.driver.maximize_window()
        self.logger.info("Maximize the current window.")
        self.driver.implicitly_wait(10)
        self.logger.info("Set implicitly wait 10 seconds.")

        return self.driver

    def login_znfz(self):
        if self.url == 'LOGIN':
            return
        username = self.get_userInfo('username')
        password = self.get_userInfo('password')
        self.logger.info("username: %s" % username)
        # logger.info(string.Formatter("username: %s, password: %s, open url: %s", username, password, url))
        # logger.info("password :%s" % password)
        # logger.info("Open url: %s" % url)
        tags = self.driver.find_element_by_xpath('//*[@id="root"]/div/div/div[2]/form/div[1]/div/div/span/span/span')
        self.logger.info("tags.text:%s" % tags.text)
        # print(tags.text)
        tags.click()
        time.sleep(1)

        self.driver.find_element_by_xpath('//*[@id="rc-tree-select-list_1"]/ul/li/ul/li[3]/span[1]').click()

        tags2 = self.driver.find_element_by_xpath(
            '//*[@id="rc-tree-select-list_1"]/ul/li/ul/li[3]/ul/li[3]/span[2]/span')
        self.logger.info("tags2.text:%s" % tags2.text)
        # print(tags2.text)
        tags2.click()
        time.sleep(1)

        self.driver.find_element_by_xpath('//*[@id="username"]').send_keys(username)
        self.driver.find_element_by_xpath('//*[@id="password"]').send_keys(password)
        self.driver.find_element_by_xpath('//*[@id="root"]/div/div/div[2]/form/div[4]/div/div/span/button').click()
        return self.driver

    def get_page(self):
        time.sleep(1)
        if self.url in ['LOGIN', 'INDEX']:
            return
        if self.url != 'URL':
            url = self.get_testUrl(self.url)
            url = url.format(bmsah=self.get_caseId('caseId')) if '{' in url else url
            self.logger.info("the testUrl : %s" % url)
            self.driver.get(url)

    def load_image(self):
        print(self.image_path)
        image_dir, image_name = os.path.split(self.image_path)
        image_list = os.listdir(image_dir)
        if image_name in image_list:
            image_name_list = list(filter(lambda x: re.findall(image_name + r'-\d{1,}\.png', x), image_list))
            image_name_index_list = list(map(lambda x: int(x.split('-|.')[-2]) if '-' in x else 0, image_name_list))
            next_image_name_index = max(image_name_index_list) + 1 if image_name_index_list else 1
            next_image_name = os.path.join(image_dir, image_name.replace('.png', f'-{next_image_name_index}.png'))
        else:
            next_image_name = self.image_path
        print(next_image_name)
        self.driver.get_screenshot_as_file(next_image_name)

    def __del__(self):
        try:
            self.driver.quit()
        except:
            pass


'''
if __name__ == '__main__':

    cls =  BrowserEngine()
    test = cls.open_browser()
    time.sleep(3)
    test.quit()
'''
