import traceback

import cv2
import numpy as np
import pytesseract
from PIL import ImageGrab, Image

from sbc.public_methods import new_print


class ScreenUtils:
    def __init__(self, public_moves_instance):
        from utils.public_moves import PublicMoves
        self.public_moves: PublicMoves = public_moves_instance
        self.fifa_account = self.public_moves.fifa_account
        self.sbc_worker = self.public_moves.sbc_worker
        self.ps4_buttons = self.public_moves.ps4_buttons

    def has_image(self, 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)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        if max_val > threshold:
            return True
        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

    def has_image_2(self, small_image, gray_frame, threshold=0.9):
        """بررسی می‌کند که آیا یک تمپلیت در صفحه وجود دارد یا نه"""
        res = cv2.matchTemplate(gray_frame, small_image, cv2.TM_CCOEFF_NORMED)
        _, max_val, _, _ = cv2.minMaxLoc(res)
        return max_val >= threshold

    def get_screen_shot(self, 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:
            new_print(self.fifa_account, 'get_screen_shot try : ', try_counter, ' --- ', traceback.format_exc())
            return self.get_screen_shot(try_counter=try_counter + 1)

    def get_screen_text(self, screen_name='', config='', convert=False, convert_type=1):

        if screen_name == '':
            self.get_screen_shot()
            screen_name = 'screen_shot_tmp.jpg'

        img = Image.open(screen_name)
        if convert:
            si = img.size
            for i in range(si[0]):
                for j in range(si[1]):
                    pixel = i, j
                    # print(img.getpixel(pixel))
                    try:
                        if img.getpixel(pixel)[0] < 80:
                            img.putpixel(pixel, (0, 0, 0))
                        else:
                            img.putpixel(pixel, (255, 255, 255))
                    except:
                        # print(img.getpixel(pixel))
                        if convert_type == 2:
                            if img.getpixel(pixel) < 150:
                                img.putpixel(pixel, 0)
                            else:
                                img.putpixel(pixel, 255)
                        else:
                            if img.getpixel(pixel) < 80:
                                img.putpixel(pixel, 0)
                            else:
                                img.putpixel(pixel, 255)

        img.save('new_part_tmp.png')

        if config:
            screen_text = pytesseract.image_to_string(img, lang='eng', config=config)
        else:
            screen_text = pytesseract.image_to_string(img, lang='eng')
        return screen_text