import cv2
import numpy as np
import pyautogui
import os
import logging
import time

TEMPLATE_FOLDER = r'C:\Bot_Hearthstone\Skreen' 
TEMPLATES = []

# Загрузка эталонных шаблонов  
for template_name in os.listdir(TEMPLATE_FOLDER):
    if template_name.endswith('.bmp'):
        template = cv2.imread(os.path.join(TEMPLATE_FOLDER, template_name), 0)
        TEMPLATES.append(template)

def find_game_window():
    windows = pyautogui.getWindowsWithTitle('Hearthstone')
    if len(windows) > 0:
        return windows[0]

def main():
    while True:
        game_wnd = find_game_window()
        if game_wnd is None:
            continue
       
        # Делаем скриншот окна   
        x1, y1, x2, y2 = game_wnd.left, game_wnd.top, game_wnd.right, game_wnd.bottom  
        screenshot = np.array(ImageGrab.grab(bbox=(x1, y1, x2, y2)))        
   
        # Работаем с шаблонами      
        screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)     
        for template in TEMPLATES:
            res = cv2.matchTemplate(screenshot_gray, template, cv2.TM_CCOEFF_NORMED)
            loc = np.where(res >= 0.9)           
            if len(loc[0]) > 0:
                # Кликаем по найденному шаблону
                x, y = pyautogui.center(loc)
                pyautogui.click(x, y)  
                
                # Ждем исчезновения  
                while True:
                    if find_template(template, screenshot_gray) is None:
                        break

log_dir = r'C:\Bot_Hearthstone'
if not os.path.exists(log_dir):
    os.makedirs(log_dir)

logging.basicConfig(filename=os.path.join(log_dir, 'Logging.log'), level=logging.INFO, format='%(asctime)s: %(message)s')


def move_mouse_smoothly(x, y, duration, comment):
    start_x, start_y = pyautogui.position()
    pyautogui.moveTo(x, y, duration=duration)
    pyautogui.click()
    logging.info(f"{comment}")


def find_and_interact_with_image(image_path, region, sleep_duration, pre_click_coords=None, optional=False, duration=1):
    image_found = False
    while not image_found:
        image_location = pyautogui.locateOnScreen(image_path, region=region, confidence=0.6)
        if image_location is not None:
            if pre_click_coords:
                for coords in pre_click_coords:
                    move_mouse_smoothly(coords[0], coords[1], duration, f"Нажал на координатах {coords}")
            else:
                image_center = pyautogui.center(image_location)
                move_mouse_smoothly(image_center[0], image_center[1], duration, f"Нажал на картинку {os.path.basename(image_path)}")
            logging.info(f"Картинка {os.path.basename(image_path)} найдена и нажата")
            image_found = True
            # Проверяем исчезновение изображения после нажатия
            while True:
                image_location_after_click = pyautogui.locateOnScreen(image_path, region=region, confidence=0.6)
                if image_location_after_click is None:
                    logging.info(f"Картинка {os.path.basename(image_path)} исчезла")
                    break
                else:
                    logging.info(f"Картинка {os.path.basename(image_path)} не исчезла, нажимаем еще раз")
                    if pre_click_coords:
                        for coords in pre_click_coords:
                            move_mouse_smoothly(coords[0], coords[1], duration, f"Нажал на координатах {coords}")
                    else:
                        image_center = pyautogui.center(image_location_after_click)
                        move_mouse_smoothly(image_center[0], image_center[1], duration, f"Нажал на картинку {os.path.basename(image_path)}")
                    time.sleep(1)  # Даем немного времени для реакции на нажатие
        elif optional:
            break
        logging.info(f"Ждем картинку {os.path.basename(image_path)}")
        time.sleep(sleep_duration)
    time.sleep(1)


def interaction_sequence(region, image_list):
    for image_path in image_list:
        image_location = pyautogui.locateOnScreen(image_path, region=region, confidence=0.6)
        if image_location is not None:
            image_center = pyautogui.center(image_location)
            move_mouse_smoothly(image_center[0], image_center[1], 1, f"Нажал на картинку {os.path.basename(image_path)}")
            logging.info(f"Картинка {os.path.basename(image_path)} найдена и нажата")
            return True
    return False


def interaction_sequence_and_click(region, image_list, click_coords):
    for image_path in image_list:
        image_location = pyautogui.locateOnScreen(image_path, region=region, confidence=0.6)
        if image_location is not None:
            image_center = pyautogui.center(image_location)
            move_mouse_smoothly(image_center[0], image_center[1], 1, f"Нажал на картинку {os.path.basename(image_path)}")
            logging.info(f"Картинка {os.path.basename(image_path)} найдена и нажата")

            move_mouse_smoothly(click_coords[0], click_coords[1], 0.5, f"Нажимаем на координаты {click_coords}")            
            return True
    return False


game_runs = 999

for _ in range(game_runs):
    windows = gw.getWindowsWithTitle('Hearthstone')
    if len(windows) > 0:
        window = windows[0]
        window.activate()

        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Vibrat.bmp'), (747, 476, 866 - 747, 527 - 476), 0.7)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Vibrat.bmp'), (700, 514, 809 - 700, 558 - 514), 1)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Podtverdit_otryad.bmp'), (377, 358, 505 - 377, 413 - 358), 0.7, optional=True)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Igrat.bmp'), (747, 464, 888 - 747, 543 - 464), 0.3)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Razigrano.bmp'), (788, 282, 897 - 788, 338 - 282), 0.5)
        time.sleep(600)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'skill_Varden.bmp'), (350, 257, 459 - 350, 357 - 257), 0.7)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'skill_Millhaus.bmp'), (350, 257, 459 - 350, 357 - 257), 0.7, duration=0.1)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'skill_Povelitel.bmp'), (453, 264, 557 - 453, 359 - 264), 0.5, duration=0.6)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'V_Boi.bmp'), (788, 282, 897 - 788, 338 - 282), 0.7)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Prodolzjit.bmp'), (443, 597, 537 - 443, 634 - 597), 0.7)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Sokrovishe.bmp'), (525, 123, 608 - 525, 169 - 123), 1, [(426, 341), (597, 548)])

        for _ in range(2):
            image_list = [os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Krasnii.bmp'),
                          os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Krasnii2.bmp'),
                          os.path.join(r'C:\Bot_Hearthstone\Skreen', 'sinii.bmp'),
                          os.path.join(r'C:\Bot_Hearthstone\Skreen', 'sinii2.bmp'),
                          os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Zelenii.bmp'),
                          os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Zelenii2.bmp')]
            while not interaction_sequence_and_click((183, 265, 621 - 183, 321 - 265), image_list, (816, 502)):
                move_mouse_smoothly(816, 502, 0.6, comment="Жмём Играть")   
                logging.info("Ждем появление цветов!")
                time.sleep(1)  
            find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Razigrano.bmp'), (788, 282, 897 - 788, 338 - 282), 0.5)
            time.sleep(600)
            find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'skill_Varden.bmp'), (350, 257, 459 - 350, 357 - 257), 0.7)
            find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'skill_Millhaus.bmp'), (350, 257, 459 - 350, 357 - 257), 0.1, duration=0.1)
            find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'skill_Povelitel.bmp'), (453, 264, 557 - 453, 359 - 264), 0.5, duration=0.6)
            find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'V_Boi.bmp'), (788, 282, 897 - 788, 338 - 282), 0.7)
            find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Prodolzjit.bmp'), (443, 597, 537 - 443, 634 - 597), 0.7)
            find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Sokrovishe.bmp'), (525, 123, 608 - 525, 169 - 123), 1, [(426, 341), (597, 548)])

        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Igrat.bmp'), (747, 464, 888 - 747, 543 - 464), 0.3)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Razigrano.bmp'), (788, 282, 897 - 788, 338 - 282), 0.5)
        time.sleep(600)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'skill_Varden.bmp'), (350, 257, 459 - 350, 357 - 257), 0.7)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'skill_Millhaus.bmp'), (350, 257, 459 - 350, 357 - 257), 0.1, duration=0.1)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'skill_Povelitel.bmp'), (453, 264, 557 - 453, 359 - 264), 0.5, duration=0.6)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'V_Boi.bmp'), (788, 282, 897 - 788, 338 - 282), 0.7)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Prodolzjit.bmp'), (443, 597, 537 - 443, 634 - 597), 0.7)
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Sunduki.bmp'), (458, 353, 590 - 458, 458 - 353), 3, [(537, 206), (352, 471), (694, 475), (524, 380)])
        find_and_interact_with_image(os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Poruchenie_vipolneno.bmp'), (431, 492, 566 - 431, 557 - 492), 0.7)
        image_path = os.path.join(r'C:\Bot_Hearthstone\Skreen', 'Vipolneno_zadanie.bmp')
        search_region = (184, 177, 831 - 184, 294 - 177)
        confidence = 0.7
        click_coords = [(330, 482), (908, 371), (908, 371), (908, 371)]

        image_location = pyautogui.locateOnScreen(image_path, region=search_region, confidence=confidence)
        if image_location is not None:
            image_center = pyautogui.center(image_location)
            pyautogui.click(image_center[0], image_center[1])
            time.sleep(1.0)
            for coords in click_coords:
                pyautogui.moveTo(coords[0], coords[1], duration=1.0)
                pyautogui.click()
                time.sleep(1.0)
        else:
            optional = True