import os
import time
import pyautogui

email_button_image_path = "D:/screensWOT/forwork/mail.png"
password_button_image_path = "D:/screensWOT/forwork/password.png"
submit_button_image_path = "D:/screensWOT/forwork/voity.png"
locationvalid_image_path = "D:/screensWOT/forwork/valid.png"
locationnevalid_image_path = "D:/screensWOT/forwork/nevalid.png"
tank_image_path = "D:/screensWOT/forwork/tank.png"
sbros_image_path = "D:/screensWOT/forwork/sbros.png"
arenda_image_path = "D:/screensWOT/forwork/arenda.png"
tops_image_path = "D:/screensWOT/forwork/tops.png"
prems_image_path = "D:/screensWOT/forwork/prems.png"
panel_image_path = "D:/screensWOT/forwork/panel.png"
topsvkl_image_path = "D:/screensWOT/forwork/topsvkl.png"
nastroyki_image_path = "D:/screensWOT/forwork/nastroyki.png"
vixod_image_path = "D:/screensWOT/forwork/vixod.png"
da_image_path = "D:/screensWOT/forwork/da.png"
stop_image_path = "D:/screensWOT/forwork/stop.png"
crestik_image_path = "D:/screensWOT/forwork/crestik.png"
crestik2_image_path = "D:/screensWOT/forwork/crestik2.png"
otkaz_image_path = "D:/screensWOT/forwork/otkaz.png"
valid_accounts_path = "D:/screensWOT/valid_accounts.txt"
nevalid_accounts_path = "D:/screensWOT/nevalid_accounts.txt"
passagir_accounts_path = "D:/screensWOT/passagir_accounts.txt"
ok_image_path = "D:/screensWOT/forwork/ok.png"
file_path = "D:/fileobuch/accsforscreens.txt"
arrays = []

with open(file_path, "r") as file:
    for line in file:
        parts = line.strip().split(":")
        arrays.append(parts)


def save_account_info(filepath, email, password):
    """Функция для сохранения логина и пароля в файл"""
    with open(filepath, "a") as file:
        file.write(f"{email}:{password}\n")


def vxod(email, password):
    timeout1 = 1  # секунды
    start_time1 = time.time()
    while time.time() - start_time1 < timeout1:
            try:
                ok = pyautogui.locateOnScreen(ok_image_path, confidence=0.8)
                if ok:
                    pyautogui.click(ok)
                    pyautogui.click(ok)
                    time.sleep(2)
                    break
            except pyautogui.ImageNotFoundException:
                pass  # Игнорируем ошибку и продолжаем цикл
    time.sleep(1)
    pyautogui.click(x=942, y=716)
    pyautogui.doubleClick(x=942, y=716)
    pyautogui.write(email)

    print("Email введен: " + email)
    locationpass = pyautogui.locateCenterOnScreen(
        password_button_image_path, confidence=0.6, grayscale=True
    )
    if locationpass:
        pyautogui.click(locationpass)
        pyautogui.click(locationpass)
        pyautogui.write(password)
        time.sleep(1)
        print("Пароль введен.")
    else:
        print("Не удалось найти поле ввода пароля.")
        return False

    locationsubmit = pyautogui.locateCenterOnScreen(
        submit_button_image_path, confidence=0.65
    )
    if locationsubmit:
        pyautogui.click(locationsubmit)
        pyautogui.click(locationsubmit)
        print("Произведен клик для входа.")
    else:
        print("Не удалось найти кнопку входа.")
        return False

    timeout = 30  # Установим таймаут в 20 секунд
    start_time = time.time()

    # Ждем появления одного из изображений на экране в течение установленного таймаута
    while True:
        try:
            locationvalid = pyautogui.locateCenterOnScreen(
                locationvalid_image_path, confidence=0.65
            )
            if locationvalid:
                print("Вход выполнен успешно.")
                save_account_info(valid_accounts_path, email, password)
                time.sleep(40)
                return True
        except pyautogui.ImageNotFoundException:
            pass  # Если изображение не найдено, пропускаем итерацию

        try:
            locationnevalid = pyautogui.locateCenterOnScreen(
                locationnevalid_image_path, confidence=0.65
            )
            if locationnevalid:
                print("Обнаружена ошибка входа.")
                save_account_info(nevalid_accounts_path, email, password)
                return False
        except pyautogui.ImageNotFoundException:
            pass  # Если изображение не найдено, пропускаем итерацию
        try:
            passagir = pyautogui.locateCenterOnScreen(stop_image_path, confidence=0.8)
            if passagir:
                print("Обнаружена ошибка входа.")
                pyautogui.click(x=958, y=637)
                time.sleep(1)
                pyautogui.click(x=959, y=637)
                time.sleep(1)
                save_account_info(passagir_accounts_path, email, password)
                return False
        except pyautogui.ImageNotFoundException:
            pass  # Если изображение не найдено, пропускаем итерацию

        time.sleep(0.5)  # Небольшая пауза между попытками
        # Если достигнут таймаут, завершаем ожидание
        if time.time() - start_time > timeout:
            print("Таймаут ожидания.")
            return False


# Программа запускается с двухсекундной задержкой
time.sleep(2)

for email, password in arrays:
    if vxod(email, password):
        # Искать изображение 'crestik'
        timeout = 3  # секунды
        start_time = time.time()
        screens_folder_path = "D:/screens/"
        while time.time() - start_time < timeout:
            try:
                crestik = pyautogui.locateOnScreen(crestik_image_path, confidence=0.9)
                if crestik:
                    print(f"Изображение 'crestik' найдено: {crestik}")
                    pyautogui.click(crestik)
                    pyautogui.click(crestik)
                    time.sleep(2)
                    break
            except pyautogui.ImageNotFoundException:
                pass  # Игнорируем ошибку и продолжаем цикл

        # Искать изображение 'crestik2'
        start_time = time.time()  # Обновляем время начала
        while time.time() - start_time < timeout:
            try:
                crestik2 = pyautogui.locateOnScreen(crestik2_image_path, confidence=0.8)
                if crestik2:
                    print(f"Изображение 'crestik2' найдено: {crestik2}")
                    pyautogui.click(crestik2)
                    pyautogui.click(crestik2)
                    time.sleep(2)
                    break
            except pyautogui.ImageNotFoundException:
                pass  # Игнорируем ошибку и продолжаем цикл
        start_time = time.time()  # Обновляем время начала
        while time.time() - start_time < timeout:
            try:
                otkaz = pyautogui.locateOnScreen(otkaz_image_path, confidence=0.8)
                if otkaz:
                    print(f"Изображение 'crestik2' найдено: {crestik2}")
                    pyautogui.click(crestik2)
                    pyautogui.click(crestik2)
                    time.sleep(2)
                    break
            except pyautogui.ImageNotFoundException:
                pass  # Игнорируем ошибку и продолжаем цикл

        # Искать изображение 'sbros'
        start_time = time.time()  # Обновляем время начала
        while time.time() - start_time < timeout:
            try:
                sbros = pyautogui.locateOnScreen(sbros_image_path, confidence=0.9)
                if sbros:
                    print(f"Изображение 'sbros' найдено: {sbros}")
                    pyautogui.click(sbros)
                    pyautogui.click(sbros)
                    time.sleep(2)
                    break
            except pyautogui.ImageNotFoundException:
                pass  # Игнорируем ошибку и продолжаем цикл
        subdir_name = f"{email}_{password}"
        subdir_path = os.path.join(screens_folder_path, subdir_name)
        if not os.path.exists(subdir_path):
            os.makedirs(subdir_path)
        time.sleep(2)
        tank = pyautogui.locateCenterOnScreen(tank_image_path, confidence=0.8)
        if tank:
            pyautogui.click(tank)
            pyautogui.click(tank)
            time.sleep(2)
            print("Клик по фильтрам")
        else:
            print("Нет кнопки фильтра")
        arenda = pyautogui.locateCenterOnScreen(arenda_image_path, confidence=0.8)
        if arenda:
            pyautogui.click(arenda)
            pyautogui.click(arenda)
            print("Клик по арендной технике")
        else:
            print("Нет кнопки аренды")
        tops = pyautogui.locateCenterOnScreen(tops_image_path, confidence=0.9)
        if tops:
            pyautogui.click(tops)
            pyautogui.click(tops)
            print("Клик по топам")
        else:
            print("Нет кнопки топов")
        end_time = time.time() + 10
        panel_found = False
        while time.time() < end_time and not panel_found:
            try:
                panel = pyautogui.locateCenterOnScreen(panel_image_path, confidence=0.9)
                if panel:
                    pyautogui.click(panel)
                    pyautogui.click(panel)
                    subdir_name = f"{email}_{password}"
                    subdir_path = os.path.join(screens_folder_path, subdir_name)
                    if not os.path.exists(subdir_path):
                        os.makedirs(subdir_path)
                    screenshot_filename = f"1tops_{time.strftime('%Y%m%d-%H%M%S')}.png"
                    screenshot_path = os.path.join(subdir_path, screenshot_filename)
                    pyautogui.screenshot(screenshot_path)
                    print(f"Скриншот сохранен: {screenshot_path}")
                    panel_found = True
                    time.sleep(2)
            except pyautogui.ImageNotFoundException:
                subdir_name = f"{email}_{password}"
                subdir_path = os.path.join(screens_folder_path, subdir_name)
                if not os.path.exists(subdir_path):
                    os.makedirs(subdir_path)
                screenshot_filename = f"1tops_{time.strftime('%Y%m%d-%H%M%S')}.png"
                screenshot_path = os.path.join(subdir_path, screenshot_filename)
                pyautogui.screenshot(screenshot_path)
                print(f"Скриншот сохранен: {screenshot_path}")
                panel_found = True
                time.sleep(2)
        prems = pyautogui.locateCenterOnScreen(prems_image_path, confidence=0.9)
        if prems:
            pyautogui.click(prems)
            pyautogui.click(prems)
            screenshot_filename = f"3topprems_{time.strftime('%Y%m%d-%H%M%S')}.png"
            screenshot_path = os.path.join(subdir_path, screenshot_filename)
            pyautogui.screenshot(screenshot_path)
            print(f"Скриншот премиум топов сохранен: {screenshot_path}")
            time.sleep(2)
        else:
            print("Нет кнопки премиум топов")
        topsvkl = pyautogui.locateCenterOnScreen(topsvkl_image_path, confidence=0.9)
        if topsvkl:
            pyautogui.click(topsvkl)
            pyautogui.click(topsvkl)
            screenshot_filename = f"2prems_{time.strftime('%Y%m%d-%H%M%S')}.png"
            screenshot_path = os.path.join(subdir_path, screenshot_filename)
            pyautogui.screenshot(screenshot_path)
            print(f"Скриншот премиум топов сохранен: {screenshot_path}")
            time.sleep(2)
        else:
            print("Нет кнопки топов")
        nastroyki = pyautogui.locateCenterOnScreen(nastroyki_image_path, confidence=0.9)
        if nastroyki:
            pyautogui.click(nastroyki)
            pyautogui.click(nastroyki)
            print("Клик по настройкам")
            time.sleep(1)
        else:
            print("Нет кнопки настроек")
        vixod = pyautogui.locateCenterOnScreen(vixod_image_path, confidence=0.9)
        if vixod:
            pyautogui.click(vixod)
            pyautogui.click(vixod)
            print("Клик по выходу")
            time.sleep(1)
        else:
            print("Нет кнопки выхода")
        da = pyautogui.locateCenterOnScreen(da_image_path, confidence=0.9)
        if da:
            pyautogui.click(da)
            pyautogui.click(da)
            print("Клик по да")
            time.sleep(4)
        else:
            print("Нет кнопки да")
    else:
        # Если вход не удался - пытаемся со следующей парой
        print("Переход к следующей паре учетных данных.")
        time.sleep(1)