import os
import time
import traceback

import cv2
import keyboard
import mouse
import numpy as np
from PIL import ImageGrab


def get_image_position(small_image_name, large_image_name):
    # http://www.learningaboutelectronics.com/Articles/How-to-match-an-image-embedded-in-another-image-Python-OpenCV.php
    image = cv2.imread(large_image_name)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    template = cv2.imread(small_image_name, 0)
    result = cv2.matchTemplate(gray, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    height, width = template.shape[:2]
    top_left = max_loc
    top_right = (top_left[0] + width, top_left[1])
    bottom_left = (top_left[0], top_left[1] + height)
    bottom_right = (top_left[0] + width, top_left[1] + height)
    # cv2.rectangle(image, top_left, bottom_right, (0, 0, 255), 5)
    # cv2.imshow('Rainforest', image)
    # cv2.waitKey(0)
    return {
        'top_left': top_left, 'top_right': top_right,
        'bottom_left': bottom_left, 'bottom_right': bottom_right,
        'width': width, 'height': height
    }


def get_screen_shot(image_name='screen_shot_tmp.jpg', try_counter=0):
    if try_counter > 10:
        raise Exception('screen shot Permission denied')
    try:
        snapshot = ImageGrab.grab()
        save_path = image_name
        snapshot.save(save_path)
    except PermissionError:
        print('get_screen_shot try : ', try_counter, ' --- ', traceback.format_exc())
        return get_screen_shot(try_counter=try_counter + 1)


def has_image(small_image_name, large_image_name, threshold=.9):
    # new_print(self.fifa_account,'has image addresses = ',small_image_name,large_image_name)
    small_image = cv2.imread(small_image_name)
    large_image = cv2.imread(large_image_name)
    small_image = cv2.cvtColor(small_image, cv2.COLOR_BGR2GRAY)
    large_image = cv2.cvtColor(large_image, cv2.COLOR_BGR2GRAY)
    w, h = large_image.shape[::-1]
    res = cv2.matchTemplate(small_image, large_image, cv2.TM_CCOEFF_NORMED)
    loc = np.where(res >= threshold)
    try:
        assert loc[0][0] > 0
        assert loc[1][0] > 0
        if loc[1][0] >= 0 and loc[0][0] >= 0:
            return True
    except:
        # new_print(self.fifa_account,traceback.format_exc())
        return False


while True:
    get_screen_shot()
    if has_image(os.path.join(
            f'utils/create_origin_images/connect_to_vm_icon.png'),
            'screen_shot_tmp.jpg'
    ):
        print('found internet icon')
        image_position = get_image_position(
            os.path.join('utils/create_origin_images/connect_to_vm_icon.png'),
            'screen_shot_tmp.jpg')
        image_position.get('top_left')
        mouse.move(image_position['top_left'][0], image_position['top_left'][1])
        mouse.click('left')
        time.sleep(1)
        mouse.move(image_position['top_left'][0], image_position['top_left'][1] + 50)
        mouse.click('left')
        time.sleep(1)
        keyboard.press_and_release('enter')
        time.sleep(5)
        print('internet changed')
    time.sleep(5)
