import time
import threading
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as ES
from selenium.webdriver.support.ui import WebDriverWait


class BT67xxWebTest():

    def __init__(self, ip):
        self.ip = ip
        self.web_thread = threading.Thread(target=self.test_update_in_thread, daemon=True)
        self.web_thread.run()
        
    def connect(self):
        self.driver = webdriver.Firefox()
        self.driver.get('http://' + self.ip)

    def login(self):
        self.driver.find_element(By.ID, 'login').send_keys("admin")
        self.driver.find_element(By.ID, 'pass').send_keys("12345")
        self.driver.find_element(By.CLASS_NAME, 'btn.btn-primary').click()
        time.sleep(0.5)

    def go_to_iap(self):
        """Переход в IAP из основного web-интерфейса"""
        self.driver.get('http://' + self.ip + '/settings.html')
        self.driver.find_element(By.ID, 'tabset1__service').click()
        self.driver.find_element(By.ID, 'dev-update').click()
        select = Select(self.driver.find_element(By.ID, 'dev_update_method'))
        select.select_by_value('manual')
        self.driver.find_element(By.ID, 'start_fw_update').click()
        # Go to IAP!
        alert = self.driver.switch_to.alert
        alert.accept()
        time.sleep(10)

    def load_file_in_iap(self):
        """Выбор файла и загрузка прошивки"""
        try:
            file_input = WebDriverWait(self.driver, 10).until(ES.presence_of_element_located((By.ID, "uploadBtn2")))
            file_input.send_keys(self.get_file_path("BT_6721xx.bin"))
            WebDriverWait(self.driver, 10).until(ES.presence_of_element_located((By.CLASS_NAME , 'btn.btn-primary-inverted'))).click()
        except:
            print("File load error!")

    def get_file_path(self, file_name):
        """Возвращает путь к файлу"""
        current_directory = os.path.dirname(os.path.abspath(__file__))
        return os.path.join(current_directory, file_name)
        
    def test_update_in_thread(self):
        success_upload_counter = 0
        self.connect()
        while (True):
            self.login()
            self.go_to_iap()
            self.load_file_in_iap()
            success_upload_counter += 1
            print("Количесвто успешных обновлений:", success_upload_counter)
            time.sleep(14)

    def test_update(self):
        self.connect()
        self.login()
        self.go_to_iap()
        self.load_file_in_iap()


def main():
    bt67xx = BT67xxWebTest("192.168.0.254")
    # bt67xx.test_update()


if __name__ == '__main__':
    main()