import math
import os
import random
import threading
import time
import traceback

import cv2

import numpy as np
from PIL import Image, ImageGrab
from django.utils import timezone
from statistics import mean

from futplus.settings import BASE_DIR
from sbc.public_methods import new_print, set_sub_log, set_sbc_status, get_image_position

if os.name == 'nt':
    import mss

class PlayFootballUtils:
    map_position = {'left_top': (815, 830), 'left_button': (815, 990),
                    'right_top': (1100, 830), 'right_button': (1100, 990)}
    map_position['width'] = map_position['right_top'][0] - map_position['left_top'][0]
    map_position['height'] = map_position['left_button'][1] - map_position['left_top'][1]

    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 start_playing(self):
        # self.press_r1 = threading.Thread(target=self.press_r1_continue)
        threading.Thread(target=self.update_minimap_data).start()
        # self.press_r1.daemon = True
        # self.press_r1.start()
        self.break_get_minimap_data = False
        new_print(self.fifa_account, 'start playing one round')
        ball_not_find_counter = 0
        not_similar_round_counter = 0
        not_find_ball_y = {'ps': 255, 'xboxs': 30000, 'xbox360': 30000}.get(self.fifa_account.platform)
        bulk_new_print = []
        fifa_account_platform = self.fifa_account.platform
        self.ps4_buttons.press_cross()
        last_r1_press_time = timezone.localtime()
        last_l1_press_time = timezone.localtime()
        last_pass_time = last_long_pass_time = timezone.localtime()
        last_not_ball_found_cross = timezone.localtime()
        last_shoot_time = timezone.localtime()
        minimap_counter = 0
        ball_not_find_time = timezone.localtime()
        last_mini_pass_time = timezone.localtime()
        last_square_time = timezone.localtime()
        triangle_status = False
        last_time = timezone.localtime()
        last_ball_found_time = timezone.localtime()
        self.round = 3
        l2_status = False
        while True:
            # new_time = timezone.localtime()
            # print('one loop time = ',str(new_time - last_time))
            # last_time = new_time
            # print('time : ', time.time() , '------------------')

            # print('time : ', time.time(), 'l1')
            # ball_position = self.get_ball_position()
            minimap_counter += 1
            # print('time : ', time.time(), 'before read')
            # print('before map time = ', str(timezone.localtime() - last_time))
            # minimap_data = self.read_minimap_data(minimap_counter=minimap_counter,loop_start_time=last_time)
            minimap_data = self.minimap_data
            # print('after map time = ', str(timezone.localtime() - last_time))
            # print('minimap_data =',minimap_data)
            # print('time : ', time.time(), 'after read')
            # print('time : ', time.time(), 'read minimap')
            ball_position = minimap_data.get('ball')
            enemy_x_num = {'ps': 255, 'xboxs': 32767, 'xbox360': 32767}.get(fifa_account_platform)
            enemy_y_num = {'ps': 125, 'xboxs': 0, 'xbox360': 0}.get(fifa_account_platform)
            if self.round == 2:
                enemy_x_num = {'ps': 0, 'xboxs': -32767, 'xbox360': -32767}.get(fifa_account_platform)
            if ball_position:
                if int(0.23 * self.map_position['width']) < ball_position[0] < int(0.73 * self.map_position['width']) or self.round == 3:
                    new_game_round = self.get_round_number()
                    if new_game_round and new_game_round != self.round:
                        not_similar_round_counter += 1
                        bulk_new_print.append(('game round not similar : ', self.round, new_game_round))
                    elif new_game_round:
                        not_similar_round_counter = 0
                        # bulk_new_print.append(('game round is similar : ', self.round, new_game_round))
                    if not_similar_round_counter > 2:
                        not_similar_round_counter = 0
                        bulk_new_print.append(('i will change round : ', self.round, new_game_round))
                        self.round = new_game_round
                # if self.round == 1 and ball_position[0] < 128 and not l2_status:
                #     self.ps4_buttons.press_l2()
                #     l2_status = True
                # elif self.round == 1 and ball_position[0] >= 128 and l2_status:
                #     self.ps4_buttons.release_l2()
                #     l2_status = False
                #
                # if self.round == 2 and ball_position[0] > 128 and not l2_status:
                #     self.ps4_buttons.press_l2()
                #     l2_status = True
                # elif self.round == 2 and ball_position[0] <= 128 and l2_status:
                #     self.ps4_buttons.release_l2()
                #     l2_status = False

                if self.round == 1 and ball_position[0] < int(0.492 * self.map_position['width']):
                    last_r1_sleep = 3.5
                    last_l1_time = 3
                elif self.round == 2 and ball_position[0] > int(0.492 * self.map_position['width']):
                    last_r1_sleep = 3.5
                    last_l1_time = 3
                else:
                    last_r1_sleep = 7
                    last_l1_time = 4

                if last_r1_press_time < timezone.localtime() - timezone.timedelta(seconds=last_r1_sleep):
                    last_r1_press_time = timezone.localtime()
                    # print('time : ', time.time() , 'r1')
                    self.ps4_buttons.release_r1(sleep_after=0.002)
                    self.ps4_buttons.press_r1(press_time=0.001)
                if last_l1_press_time < timezone.localtime() - timezone.timedelta(
                        seconds=last_l1_time) and last_pass_time < timezone.localtime() - timezone.timedelta(seconds=2) \
                        and last_shoot_time < timezone.localtime() - timezone.timedelta(seconds=2):
                    last_l1_press_time = timezone.localtime()
                    self.ps4_buttons.l1(press_time=.01, sleep_after=0)
                    self.ps4_buttons.release_r1(sleep_after=0.002)
                    self.ps4_buttons.press_r1(press_time=0.001)

                # print('time : ', time.time(), 'ball found')
                ball_not_find_counter = 0
                last_ball_found_time = timezone.localtime()
                # bulk_new_print.append(('ball position x,y : ', ball_position))

                # if self.round == 1 and ball_position[0] < 110 and not self.l2_status:
                #     print('press l2 for jockey')
                #     self.ps4_buttons.press_l2()
                #     self.l2_status = 1
                # elif self.round == 1 and ball_position[0] >= 110 and self.l2_status:
                #     print('release l2 for jockey')
                #     self.ps4_buttons.release_l2()
                #     self.l2_status = 0
                # if self.round == 2 and ball_position[0] > 146 and not self.l2_status:
                #     print('press l2 for jockey')
                #     self.ps4_buttons.press_l2()
                #     self.l2_status = 1
                # elif self.round == 2 and ball_position[0] <= 110 and self.l2_status:
                #     print('release l2 for jockey')
                #     self.ps4_buttons.release_l2()
                #     self.l2_status = 0

                if (self.round == 1 and
                        ball_position[0] < int(0.153 * self.map_position['width']) and
                        last_mini_pass_time < timezone.localtime() - timezone.timedelta(seconds=0.8)):
                    self.ps4_buttons.release_cross(sleep_after=0.1)
                    # self.ps4_buttons.cross()
                    self.ps4_buttons.press_cross(press_time=0.001)
                    last_mini_pass_time = timezone.localtime()
                elif (self.round == 2 and
                      ball_position[0] > int(0.846 * self.map_position['width']) and
                      last_mini_pass_time < timezone.localtime() - timezone.timedelta(seconds=0.8)):
                    self.ps4_buttons.release_cross(sleep_after=0.1)
                    # self.ps4_buttons.cross()
                    self.ps4_buttons.press_cross(press_time=0.001)
                    last_mini_pass_time = timezone.localtime()
                # print('time : ', time.time(), 'round number check')
                if (self.round == 1 and
                        (ball_position[0] < int(0.561 * self.map_position['width']) or ball_position[0] > int(0.846 * self.map_position['width'])) and
                        self.r2_status == 1 and
                        last_long_pass_time < timezone.localtime() - timezone.timedelta(seconds=2)):
                    # bulk_new_print.append(('ball_position = ', ball_position, ' near gol position release r2'))
                    self.ps4_buttons.release_r2(sleep_after=0.1)
                    self.r2_status = 0
                # elif not self.r2_status:
                #     self.ps4_buttons.press_r2(sleep_after=0)
                #     self.r2_status = 1
                if (self.round == 2 and
                        (ball_position[0] > int(0.442 * self.map_position['width']) or ball_position[0] < int(0.153 * self.map_position['width'])) and
                        self.r2_status == 1 and
                        last_long_pass_time < timezone.localtime() - timezone.timedelta(seconds=2)):
                    # bulk_new_print.append(('ball_position = ', ball_position, ' near gol position release r2'))
                    self.ps4_buttons.release_r2(sleep_after=0.1)
                    self.r2_status = 0
                # elif not self.r2_status:
                #     self.ps4_buttons.press_r2(sleep_after=0)
                #     self.r2_status = 1
                if self.round == 1 and ball_position[0] > int(0.865 * self.map_position['width']) and (int(0.675 * self.map_position['height']) > ball_position[1] > int(0.281 * self.map_position['height'])):
                    # bulk_new_print.append(('ball_position = ', ball_position, ' shoot'))
                    # print('want to shoot ball position',ball_position)
                    # if ball_position[1] < 42:
                    #     self.ps4_buttons.press_left_joystick_float(0, -1, press_time=.1)
                    #     if last_pass_time < timezone.localtime() - timezone.timedelta(seconds=1):
                    #
                    #         self.ps4_buttons.release_cross(sleep_after=0.1)
                    #         # self.ps4_buttons.cross()
                    #         self.ps4_buttons.press_cross(press_time=0)
                    #         last_pass_time = timezone.localtime()
                    #         continue
                    # elif ball_position[1] > 112:
                    #     self.ps4_buttons.press_left_joystick_float(0, 1, press_time=.1)
                    #     if last_pass_time < timezone.localtime() - timezone.timedelta(seconds=1):
                    #
                    #         self.ps4_buttons.release_cross(sleep_after=0.1)
                    #         # self.ps4_buttons.cross()
                    #         self.ps4_buttons.press_cross(press_time=0)
                    #         last_pass_time = timezone.localtime()
                    #         continue
                    self.shoot(minimap_data)
                    last_shoot_time = timezone.localtime()
                elif self.round == 2 and ball_position[0] < int(0.135 * self.map_position['width']) and (int(0.675 * self.map_position['height']) > ball_position[1] > int(0.281 * self.map_position['height'])):
                    # print('want to shoot ball position', ball_position)
                    # bulk_new_print.append(('ball_position = ', ball_position, ' shoot'))
                    # if ball_position[1] < 42:
                    #     self.ps4_buttons.press_left_joystick_float(0, -1, press_time=.1)
                    #     if last_pass_time < timezone.localtime() - timezone.timedelta(seconds=1):
                    #
                    #         self.ps4_buttons.release_cross(sleep_after=0.1)
                    #         # self.ps4_buttons.cross()
                    #         self.ps4_buttons.press_cross(press_time=0)
                    #         last_pass_time = timezone.localtime()
                    #         continue
                    # elif ball_position[1] > 112:
                    #     self.ps4_buttons.press_left_joystick_float(0, 1, press_time=.1)
                    #     if last_pass_time < timezone.localtime() - timezone.timedelta(seconds=1):
                    #
                    #         self.ps4_buttons.release_cross(sleep_after=0.1)
                    #         # self.ps4_buttons.cross()
                    #         self.ps4_buttons.press_cross(press_time=0)
                    #         last_pass_time = timezone.localtime()
                    #         continue
                    self.shoot(minimap_data)
                    last_shoot_time = timezone.localtime()
                elif (abs(self.get_frontest(minimap_data.get('enemy_team'), self.round)[0] - ball_position[0])
                      < int(0.141 * self.map_position['width']) and (
                              int(0.675 * self.map_position['height']) >
                              ball_position[1] > int(0.281 * self.map_position['height']))
                ):
                    self.shoot(minimap_data)
                    last_shoot_time = timezone.localtime()

                # print('time : ', time.time(), 'r2 and shoot')

                elif len(minimap_data.get('my_team', '')) < 11:
                    if triangle_status:
                        self.ps4_buttons.release_triangle()
                        triangle_status = False
                    #
                    # print('item_2[0] : ',item_2)
                    # print('nearest_enemy[0] : ',nearest_enemy)
                    # nearest_enemy = self.get_nearest_point(minimap_data.get('ball'), minimap_data.get('enemy_team'))
                    # if self.round == 1:
                    #     if (not (minimap_data.get('ball')[0] - 12 < nearest_enemy[0] < minimap_data.get('ball')[0] + 12 and
                    #             minimap_data.get('ball')[1] - 12 < nearest_enemy[1] < minimap_data.get('ball')[1] + 12)) and \
                    #         minimap_data.get('ball')[0] > 170 and last_pass_time < timezone.localtime() - timezone.timedelta(seconds=4):
                    #             self.shoot(minimap_data,power_shoot=True)
                    #             last_pass_time = timezone.localtime()
                    # elif self.round == 2:
                    #     if (not (minimap_data.get('ball')[0] - 12 < nearest_enemy[0] < minimap_data.get('ball')[0] + 12 and
                    #             minimap_data.get('ball')[1] - 12 < nearest_enemy[1] < minimap_data.get('ball')[1] + 12)) and \
                    #         minimap_data.get('ball')[0] < 90 and last_pass_time < timezone.localtime() - timezone.timedelta(seconds=4):
                    #             self.shoot(minimap_data,power_shoot=True)
                    #             last_pass_time = timezone.localtime()

                    pass_best_player = self.passing_best_player(
                        minimap_data.get('ball'), minimap_data.get('my_team'), minimap_data.get('enemy_team'),
                        self.round
                    )
                    # print('pass_best_player',pass_best_player)
                    frontest_target_item = self.get_frontest(minimap_data.get('my_team'), self.round)
                    frontest_target = frontest_target_item[0]
                    second_behid_target = self.get_second_behindest(minimap_data.get('enemy_team'), 3 - self.round)[0]

                    if (self.round == 1 and
                            (minimap_data.get('ball')[0] < int(0.776 * self.map_position['width'])) and
                            self.r2_status == 0 and
                            (minimap_data.get('ball')[0] > frontest_target) and
                            last_long_pass_time < timezone.localtime() - timezone.timedelta(seconds=2)):
                        # bulk_new_print.append(('ball_position = ', ball_position, ' near gol position release r2'))
                        self.ps4_buttons.press_r2(sleep_after=0.001)
                        self.r2_status = 1
                    if (self.round == 2 and
                            (minimap_data.get('ball')[0] > int(0.226 * self.map_position['width'])) and
                            (minimap_data.get('ball')[0] < frontest_target) and
                            self.r2_status == 0 and
                            last_long_pass_time < timezone.localtime() - timezone.timedelta(seconds=2)):
                        # bulk_new_print.append(('ball_position = ', ball_position, ' near gol position release r2'))
                        self.ps4_buttons.press_r2(sleep_after=0.001)
                        self.r2_status = 1
                    # print('time : ', time.time(), 'after find best pass' ,second_behid_target , frontest_target)
                    # if self.round == 1 and (0 < second_behid_target - frontest_target < 8 and minimap_data.get('ball')[0] < frontest_target - 20) and 130 < frontest_target < 190 and (last_pass_time < timezone.localtime() - timezone.timedelta(seconds=4)):
                    # elif self.round == 2 and (0 < frontest_target - second_behid_target < 8 and minimap_data.get('ball')[0] > frontest_target - 20) and 130 > frontest_target > 70 and (last_pass_time < timezone.localtime() - timezone.timedelta(seconds=4)):

                    if (self.round == 1 and
                            ((0 < second_behid_target - frontest_target) and
                             (minimap_data.get('ball')[0] < frontest_target - 4)) and
                            (int(0.423 * self.map_position['width']) < frontest_target < int(0.807 * self.map_position['width'])) and
                            (last_pass_time < timezone.localtime() - timezone.timedelta(seconds=2))):
                        # print('long pass position',minimap_data.get('ball') , frontest_target,timezone.localtime())
                        self.long_pass(minimap_data, second_behid_target - frontest_target)
                        last_pass_time = timezone.localtime()
                        last_long_pass_time = timezone.localtime()

                        # large_image = minimap_data.get('map')
                        # large_image.putpixel((minimap_data.get('ball')[0], minimap_data.get('ball')[1]), (0, 0, 0))
                        # large_image.putpixel((frontest_target_item[0], frontest_target_item[1]), (0, 0, 0))
                        # large_image.save(f'minimap/{minimap_counter}_long_pass_tmp.png')

                    elif (self.round == 2 and
                          ((0 < frontest_target - second_behid_target) and
                           (minimap_data.get('ball')[0] > frontest_target + 4)) and
                          (int(0.557 * self.map_position['width']) > frontest_target > int(0.192 * self.map_position['width'])) and
                          (last_pass_time < timezone.localtime() - timezone.timedelta(seconds=2))):

                        # print('long pass position',minimap_data.get('ball') , frontest_target,timezone.localtime())
                        self.long_pass(minimap_data, frontest_target - second_behid_target)
                        last_pass_time = timezone.localtime()
                        last_long_pass_time = timezone.localtime()

                        # large_image = minimap_data.get('map')
                        # large_image.putpixel((minimap_data.get('ball')[0], minimap_data.get('ball')[1]), (0, 0, 0))
                        # large_image.putpixel((frontest_target_item[0], frontest_target_item[1]), (0, 0, 0))
                        # large_image.save(f'minimap/{minimap_counter}_long_pass_tmp.png')
                    elif pass_best_player and last_pass_time < timezone.localtime() - timezone.timedelta(seconds=3):
                        pass_compass = self.calculate_initial_compass_bearing(minimap_data.get('ball'),
                                                                              pass_best_player)
                        # print('pass compass : ', pass_compass)
                        friend_x_num, friend_y_num = self.get_xbox_x_y_with_compass(pass_compass, float_xy=True)
                        # print('pass to compass ', friend_x_num, friend_y_num)
                        # self.ps4_buttons.press_left_joystick(friend_x_num, friend_y_num, sleep_after=1)
                        self.ps4_buttons.press_left_joystick_float(friend_x_num, friend_y_num, press_time=.5)
                        self.ps4_buttons.release_cross(sleep_after=0.1)
                        self.ps4_buttons.press_cross(press_time=.5)
                        # large_image = Image.open('minimap_screenshot_tmp.png')
                        # large_image.putpixel((minimap_data.get('ball')[0], minimap_data.get('ball')[1]), (0, 0, 0))
                        # large_image.putpixel((pass_best_player[0], pass_best_player[1]), (0, 0, 0))
                        # large_image.save(f'minimap/{minimap_counter}_pass_tmp.png')
                        last_pass_time = timezone.localtime()
                    elif (last_square_time < timezone.localtime() - timezone.timedelta(seconds=2) and
                          (self.round == 1 and
                           minimap_data.get('ball')[0] > int(0.807 * self.map_position['width']) and
                           (minimap_data.get('ball')[1] < 41 or minimap_data.get('ball')[1] > 114))
                    ):
                        if minimap_data.get('ball')[1] < 41:
                            self.ps4_buttons.release_r1(sleep_after=0)
                            self.ps4_buttons.press_left_joystick_float(0, -1, press_time=0)
                            self.ps4_buttons.square(sleep_after=0.001)
                        elif minimap_data.get('ball')[1] > 114:
                            self.ps4_buttons.release_r1(sleep_after=0)
                            self.ps4_buttons.press_left_joystick_float(0, 1, press_time=0)
                            self.ps4_buttons.square(sleep_after=0.001)
                        last_square_time = timezone.localtime()
                    elif (last_square_time < timezone.localtime() - timezone.timedelta(seconds=2) and
                          (self.round == 2 and
                           minimap_data.get('ball')[0] < int(0.192 * self.map_position['width']) and
                           (minimap_data.get('ball')[1] < 41 or minimap_data.get('ball')[1] > 114))
                    ):
                        if minimap_data.get('ball')[1] < 41:
                            self.ps4_buttons.release_r1(sleep_after=0)
                            self.ps4_buttons.press_left_joystick_float(0, -1, press_time=0)
                            self.ps4_buttons.square(sleep_after=0.001)
                        elif minimap_data.get('ball')[1] > 114:
                            self.ps4_buttons.release_r1(sleep_after=0)
                            self.ps4_buttons.press_left_joystick_float(0, 1, press_time=0)
                            self.ps4_buttons.square(sleep_after=0.001)
                        last_square_time = timezone.localtime()
                    else:
                        best_move_compass = self.move_best_direction(
                            minimap_data.get('ball'), minimap_data.get('my_team'), minimap_data.get('enemy_team'),
                            self.round
                        )
                        try:
                            move_x_num, move_y_num = self.get_xbox_x_y_with_compass(best_move_compass[0], float_xy=True)
                            # print('move to direction : ', best_move_compass[0], ' move x y : ',)
                            self.ps4_buttons.press_left_joystick_float(move_x_num, move_y_num, press_time=0.001)
                        except:
                            print('best move compass', best_move_compass)
                            print(traceback.format_exc())
                        # if len(minimap_data.get('my_team','')) < 11:
                        #     large_image = Image.open('minimap_screenshot_tmp.png')
                        #     x_pos = minimap_data.get('ball')[0]
                        #     y_pos = minimap_data.get('ball')[1]
                        #     large_image.putpixel((int(x_pos), int(y_pos)), (255, 255, 255))
                        #     try:
                        #         for i in range(10):
                        #             x_pos += move_x_num
                        #             y_pos += move_y_num
                        #             large_image.putpixel((int(x_pos), int(y_pos)), (0, 0, 0))
                        #     except:
                        #         pass
                        #     large_image.save(f'minimap/{minimap_counter}_move_tmp.png')

                elif len(minimap_data.get('my_team', '')) == 11:

                    if self.round == 1 and minimap_data.get('ball')[0] < int(0.492 * self.map_position['width']):
                        # if (last_backward_time < timezone.localtime() - timezone.timedelta(seconds=6))  and minimap_data.get('ball')[0] > 58:
                        #     self.ps4_buttons.press_left_joystick_float(-1, 0, press_time=0.01)
                        #     self.ps4_buttons.release_cross(sleep_after=0.01)
                        #     last_backward_time = timezone.localtime()
                        # elif (last_backward_time < timezone.localtime() - timezone.timedelta(seconds=1.5)):
                        #     self.ps4_buttons.press_cross(press_time=0.001)
                        # self.ps4_buttons.press_left_joystick_float(-1, 0, press_time=0.001)
                        if not self.r2_status:
                            self.ps4_buttons.press_r2(sleep_after=0.01)
                            self.r2_status = 1
                        # goaler_item = self.get_frontest(minimap_data.get('my_team'), 3 - self.round)
                        last_defence_item = self.get_second_behindest(minimap_data.get('my_team'), self.round)[0]
                        if (minimap_data.get('ball')[0] <= last_defence_item and
                                minimap_data.get('ball')[0] > int(0.096 * self.map_position['width']) and
                                31 < minimap_data.get('ball')[1] < 123):
                            self.ps4_buttons.press_triangle()
                            triangle_status = True
                    elif self.round == 2 and minimap_data.get('ball')[0] > int(0.492 * self.map_position['width']):
                        # if (last_backward_time < timezone.localtime() - timezone.timedelta(seconds=6)) and minimap_data.get('ball')[0] < 200:
                        #     self.ps4_buttons.press_left_joystick_float(1, 0, press_time=0.01)
                        #     self.ps4_buttons.release_cross(sleep_after=0.01)
                        #     last_backward_time = timezone.localtime()
                        # elif (last_backward_time < timezone.localtime() - timezone.timedelta(seconds=1.5)):
                        #     self.ps4_buttons.press_cross(press_time=0.001)
                        # self.ps4_buttons.press_left_joystick_float(1, 0, press_time=0.001)
                        if not self.r2_status:
                            self.ps4_buttons.press_r2(sleep_after=0.01)
                            self.r2_status = 1
                        last_defence_item = self.get_second_behindest(minimap_data.get('my_team'), self.round)[0]
                        if (minimap_data.get('ball')[0] >= last_defence_item and
                                minimap_data.get('ball')[0] < int(0.903 * self.map_position['width']) and
                                31 < minimap_data.get('ball')[1] < 123):
                            self.ps4_buttons.press_triangle()
                            triangle_status = True
                # print('time : ', time.time(), 'end')

                # if ball_position[1] > 90:
                #     enemy_y_num = {'ps': 200, 'xboxs': 30000, 'xbox360': 30000}.get(fifa_account_platform)
                # elif ball_position[1] < 60:
                #     enemy_y_num = {'ps': 50, 'xboxs': -30000, 'xbox360': -30000}.get(fifa_account_platform)
                # # bulk_new_print.append((self.fifa_account, 'enemy y num : ', ball_position[1], enemy_y_num))
                # self.ps4_buttons.press_left_joystick(enemy_x_num, enemy_y_num, sleep_after=0)


            else:
                # if bulk_new_print:
                #     new_print(self.fifa_account, bulk_list=bulk_new_print)
                bulk_new_print = []
                # new_print(self.fifa_account, 'can not find ball. ball counter = ', ball_not_find_counter)

                if ball_not_find_counter == 0:
                    ball_not_find_time = timezone.localtime()
                ball_not_find_counter += 1
                squad_battle_sign = False
                if (not self.map) and ball_not_find_time < timezone.localtime() - timezone.timedelta(seconds=2):
                    self.ps4_buttons.release_left_joystick()
                    self.public_moves.get_screen_shot()
                    if (not self.map) and self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/corner_sign.png'),
                            'screen_shot_tmp.jpg'):
                        # print('its a corner')
                        # if self.round == 1:
                        #     self.ps4_buttons.press_left_joystick_float(-1, 0, press_time=0.1)
                        # else:
                        #     self.ps4_buttons.press_left_joystick_float(1, 0, press_time=0.1)
                        # self.ps4_buttons.press_left_joystick_float(0, 0, press_time=0.01)
                        self.ps4_buttons.square(press_time=0.3)
                        # self.ps4_buttons.press_left_joystick_float(0, 0, press_time=0.01)
                    if (not self.map) and self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/squad_battle_in_game.png'),
                            'screen_shot_tmp.jpg'):
                        self.ps4_buttons.circle()
                        time.sleep(0.5)
                        squad_battle_sign = True
                if (not self.map) and ball_not_find_time < timezone.localtime() - timezone.timedelta(seconds=5):
                    # self.public_moves.get_screen_shot()
                    if (self.public_moves.has_image(os.path.join(
                            BASE_DIR, f'utils/{self.fifa_account.platform}_controls/r2_player_search.png'),
                            'screen_shot_tmp.jpg') or self.public_moves.has_image(os.path.join(
                        BASE_DIR, f'utils/{self.fifa_account.platform}_controls/r2_recently_met.png'),
                            'screen_shot_tmp.jpg')):
                        new_print(self.fifa_account, 'connect to other players page found')
                        self.public_moves.errors()
                        time.sleep(1)
                        continue
                    if self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/instant_replay_2.png'),
                            'screen_shot_tmp.jpg'
                    ):
                        new_print(self.fifa_account, 'resume (instant reply 2) found')
                        self.break_press_r1 = True
                        self.public_moves.release_buttons_after_game()
                        time.sleep(1)
                        self.ps4_buttons.circle()
                        time.sleep(1)
                        self.ps4_buttons.left()
                        time.sleep(1)
                        return 'its done'
                    if self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/instant_replay.png'),
                            'screen_shot_tmp.jpg'
                    ):
                        new_print(self.fifa_account, 'resume (instant reply) found')
                        self.break_press_r1 = True
                        self.public_moves.release_buttons_after_game()
                        time.sleep(1)
                        self.ps4_buttons.left()
                        time.sleep(1)
                        return 'its done'

                    if self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/resume_match.png'),
                            'screen_shot_tmp.jpg'
                    ):
                        new_print(self.fifa_account, 'resume found')
                        self.break_press_r1 = True
                        self.public_moves.release_buttons_after_game()
                        time.sleep(1)
                        return 'its done'

                    if (not self.map) and self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/opponent_select.png'),
                            'screen_shot_tmp.jpg'):
                        new_print(self.fifa_account, 'opponent select')
                        self.break_press_r1 = True
                        self.public_moves.release_buttons_after_game()
                        return 'game was done'
                    elif (not self.map) and (self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/advance_for_end_of_the_match.png'),
                            'screen_shot_tmp.jpg') or self.public_moves.has_image(
                        os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/after_squad_game_1.png'),
                        'screen_shot_tmp.jpg') or self.public_moves.has_image(
                        os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/after_squad_game_2.png'),
                        'screen_shot_tmp.jpg'
                    )):
                        new_print(self.fifa_account, 'advance end of game or after game 1 or 2 found')
                        self.break_press_r1 = True
                        self.public_moves.release_buttons_after_game()
                        time.sleep(1)
                        return 'game is done'
                    elif (not self.map) and (self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/win_squad_game_sign.png'),
                            'screen_shot_tmp.jpg') or self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/win_moments_game_sign.png'),
                            'screen_shot_tmp.jpg')):
                        new_print(self.fifa_account, 'win status found , game is done')
                        self.break_press_r1 = True
                        self.public_moves.release_buttons_after_game()
                        time.sleep(1)
                        return 'game is done'
                    if self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/resume_match_2.png'),
                            'screen_shot_tmp.jpg'
                    ):
                        new_print(self.fifa_account, 'resume match 2 founded')
                        self.public_moves.release_buttons_after_game()
                        time.sleep(1)
                        self.ps4_buttons.cross()
                        # self.ps4_buttons.press_cross()
                        time.sleep(2)
                        return 'its done'
                    elif (not self.map) and self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/need_help.png'), 'screen_shot_tmp.jpg'):
                        new_print(self.fifa_account, 'need_help found')
                        for nt in range(3):
                            self.ps4_buttons.circle()
                            time.sleep(1)
                            self.public_moves.get_screen_shot()
                            if self.public_moves.has_image(
                                    os.path.join(BASE_DIR,
                                                 f'utils/{self.fifa_account.platform}_controls/injure_middle_game.png'),
                                    'screen_shot_tmp.jpg'
                            ):
                                new_print(self.fifa_account, 'injury found')
                                self.ps4_buttons.release_cross()
                                self.public_moves.errors()
                                self.ps4_buttons.press_cross()
                        # self.break_press_r1 = True
                        # self.public_moves.release_buttons_after_game()
                        # time.sleep(2)
                        # return 'its done'
                    # if self.public_moves.has_image(os.path.join(
                    #         BASE_DIR,
                    #         f'utils/{self.fifa_account.platform}_controls/penalty_sign.png'),
                    #         'screen_shot_tmp.jpg'):
                    #     self.ps4_buttons.press_left_joystick_float(0, -1, press_time=.1)
                    #     self.ps4_buttons.circle()

                if ball_not_find_counter > 10:
                    if self.public_moves.just_find_state():
                        new_print(self.fifa_account, 'state found. game was done , state : ', self.public_moves.just_find_state())
                        self.break_press_r1 = True
                        self.public_moves.release_buttons_after_game()
                        time.sleep(1)
                        return 'game was done'
                    elif self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/penalty_kick_selection.png'),
                            'screen_shot_tmp.jpg'):
                        new_print(self.fifa_account, 'find penalty kick selection')
                        self.ps4_buttons.reset_to_default()
                        for iin in range(5):
                            self.ps4_buttons.up()
                            self.ps4_buttons.cross()

                    elif ball_not_find_counter >= 30 and ball_not_find_counter % 10 == 0:
                        new_print(self.fifa_account, 'can not find ball in 30 time. check errors')
                        self.ps4_buttons.reset_to_default()
                        self.public_moves.get_screen_shot()
                        errors_result = self.public_moves.errors()
                        if errors_result:
                            self.public_moves.errors()
                    else:
                        self.ps4_buttons.release_cross()
                        # self.ps4_buttons.cross()
                        self.ps4_buttons.press_cross()
                        # new_print(self.fifa_account, 'can not find ball. press cross')
                        time.sleep(0.5)

                    if ball_not_find_counter % 10 == 0:
                        if self.public_moves.has_image(os.path.join(
                                BASE_DIR,
                                f'utils/{self.fifa_account.platform}_controls/select_side_middle_game.png'),
                                'screen_shot_tmp.jpg'):
                            new_print(self.fifa_account, 'find select side middle game that mean connection lost')
                            self.break_press_r1 = True
                            self.public_moves.release_buttons_after_game()
                            time.sleep(1)
                            self.public_moves.close_game()
                            time.sleep(5)
                            self.public_moves.login_to_account()
                            time.sleep(5)
                            self.public_moves.go_to_state('ps4_main', 'home_main')
                            return 'game was done'
                        elif self.public_moves.has_image(os.path.join(
                                BASE_DIR,
                                f'utils/{self.fifa_account.platform}_controls/resume_match_after_injury.png'),
                                'screen_shot_tmp.jpg'):
                            new_print(self.fifa_account, 'resume after injury found')
                            self.ps4_buttons.reset_to_default()
                            time.sleep(1)
                            for nnt in range(3):
                                self.ps4_buttons.circle()
                                time.sleep(5)
                        elif ball_not_find_counter % 20 == 0:
                            new_print(self.fifa_account, f'can not find ball {ball_not_find_counter}. press circle')
                            self.ps4_buttons.reset_to_default()
                            time.sleep(1)
                            self.ps4_buttons.circle()
                            time.sleep(1)

                        else:
                            new_print(self.fifa_account, f'can not find ball {ball_not_find_counter}. press cross')
                            self.ps4_buttons.reset_to_default()
                            time.sleep(1)
                            self.ps4_buttons.cross()
                            # self.ps4_buttons.press_cross()
                            time.sleep(1)

                    if ball_not_find_counter and ball_not_find_counter % 60 == 0:
                        self.sbc_worker.refresh_from_db()
                        new_print(self.fifa_account, f'can not find ball more than {ball_not_find_counter}')
                        self.sbc_worker.status = f'can not find ball more than {ball_not_find_counter}'
                        # self.sbc_worker.status_change_time = timezone.localtime()
                        self.sbc_worker.save()

                    if ball_not_find_counter and ball_not_find_counter > 60 and ball_not_find_counter % 10 == 0:
                        new_print(self.fifa_account, 'can not find ball , try to press 10 circle')
                        self.ps4_buttons.reset_to_default()
                        time.sleep(1)
                        for nnt in range(10):
                            self.ps4_buttons.circle()
                            time.sleep(1)

                    if last_ball_found_time < timezone.localtime() - timezone.timedelta(minutes=20):
                        new_print(self.fifa_account, f'can not find ball more than 20 minute')
                        self.public_moves.release_buttons_after_game()
                        self.sbc_worker.refresh_from_db()
                        self.sbc_worker.status = f'can not find ball more than 20 minute'
                        self.sbc_worker.save()
                        return 'game was done'

                if ball_not_find_counter % 2 != 0:
                    self.ps4_buttons.press_l1()
                    self.ps4_buttons.press_r1()
                    self.ps4_buttons.release_l1()
                    self.ps4_buttons.release_r1()

                self.ps4_buttons.reset_to_default()
                self.r2_status = 0
                self.ps4_buttons.press_left_joystick(enemy_x_num, not_find_ball_y)
                # self.ps4_buttons.press_left_joystick_float(0, 1, press_time=0.01)
                if (last_not_ball_found_cross < timezone.localtime() - timezone.timedelta(
                        seconds=1.5) and not squad_battle_sign) or (
                        last_not_ball_found_cross < timezone.localtime() - timezone.timedelta(
                    seconds=6) and squad_battle_sign):
                    self.ps4_buttons.release_cross()
                    self.ps4_buttons.press_cross()
                    last_pass_time = timezone.localtime()
                    last_not_ball_found_cross = timezone.localtime()
                # self.ps4_buttons.release_left_joystick()

                if ball_not_find_counter > 10:
                    time.sleep(1)

    def read_minimap_data(self, screen_name='minimap_screenshot_tmp.png', minimap_counter=0,
                          loop_start_time=timezone.localtime()):
        # print('before',timezone.localtime() - loop_start_time)
        # large_image = self.get_screen_from_minimap(minimap_counter=minimap_counter,return_pic=True)
        # monitor = {"top": 830, "left": 835, "width": 260, "height": 155}
        monitor = {"top": self.map_position['left_top'][1], "left": self.map_position['left_top'][0],
                   "width": self.map_position['width'], "height": self.map_position['height']}
        with mss.mss() as sct:
            img_array = np.array(sct.grab(monitor))
        # print('after get screen = ',timezone.localtime() - loop_start_time)
        large_image = Image.fromarray(img_array)
        # print('after get screen 2 = ', timezone.localtime() - loop_start_time)
        # exit()

        # large_image_name = self.get_screen_from_minimap(minimap_counter=minimap_counter)
        # large_image = Image.open(large_image_name)
        # large_image = Image.open('minimap_screenshot_tmp.png')

        width, height = large_image.size
        # width = len(img_array[0])
        # height = len(img_array)
        pixels = large_image.load()
        # pixels = img_array
        my_team_positions = []
        enemy_team_positions = []
        enemy_dic_x = {}
        enemy_dic_y = {}
        team_dic_x = {}
        team_dic_y = {}
        ball_x_list = []
        ball_y_list = []
        for x in (range(width)):
            for y in (range(height)):
                current_pixel = pixels[x, y]
                # continue
                # if (
                #
                #         210 < current_pixel[0] < 260 and
                #         135 < current_pixel[1] < 195 and
                #         0 < current_pixel[2] < 45
                # ):
                if (

                        0 < current_pixel[0] < 70 and
                        130 < current_pixel[1] < 200 and
                        180 < current_pixel[2] < 256
                ):
                    ball_x_list.append(x)
                    ball_y_list.append(y)

                    # large_image.putpixel((x, y), (0, 0, 0))
                    # return (x, y)
                # if (
                #
                #         140 < current_pixel[0] < 205 and
                #         10 < current_pixel[1] < 50 and
                #         0 < current_pixel[2] < 50
                # ):
                if (

                        10 < current_pixel[0] < 60 and
                        10 < current_pixel[1] < 50 and
                        180 < current_pixel[2] < 256
                ):
                    bad_item = False
                    bad_item_parent = False
                    for item in my_team_positions:
                        if (x - 8 < item[0] < x + 8) and (y - 8 < item[1] < y + 8):
                            bad_item = True
                            bad_item_parent = item
                            break
                    if not bad_item:
                        my_team_positions.append((x, y))
                        # large_image.putpixel((x, y), (10, 10, 10))
                    else:
                        if bad_item_parent in team_dic_x.keys():
                            team_dic_x[bad_item_parent].append(x)
                            team_dic_y[bad_item_parent].append(y)
                        else:
                            team_dic_x[bad_item_parent] = [bad_item_parent[0]]
                            team_dic_y[bad_item_parent] = [bad_item_parent[1]]

                # if (
                #         32 < current_pixel[0] < 75 and
                #         70 < current_pixel[1] < 95 and
                #         100 < current_pixel[2] < 180
                # ):
                if (
                        125 < current_pixel[0] < 200 and
                        50 < current_pixel[1] < 100 and
                        20 < current_pixel[2] < 80
                ):
                    bad_item_2 = False
                    bad_item_2_parent = False
                    for item_2 in enemy_team_positions:
                        if (x - 8 < item_2[0] < x + 8) and (y - 8 < item_2[1] < y + 8):
                            bad_item_2 = True
                            bad_item_2_parent = item_2
                            break
                    if not bad_item_2:
                        enemy_team_positions.append((x, y))
                        # large_image.putpixel((x, y), (20, 20, 20))
                    else:
                        if bad_item_2_parent in enemy_dic_x.keys():
                            enemy_dic_x[bad_item_2_parent].append(x)
                            enemy_dic_y[bad_item_2_parent].append(y)
                        else:
                            enemy_dic_x[bad_item_2_parent] = [bad_item_2_parent[0]]
                            enemy_dic_y[bad_item_2_parent] = [bad_item_2_parent[1]]

        # print('enemy dic =',team_dic_x,enemy_dic_y)
        # large_image.save(f'minimap/{minimap_counter}_tmp.png')
        # print('after first data analyse = ', timezone.localtime() - loop_start_time)
        new_enemy_team = []
        new_my_team = []
        for enemy in enemy_dic_x:
            new_enemy_team.append((int(mean(enemy_dic_x[enemy])), int(mean(enemy_dic_y[enemy]))))
            # img_array[(int(mean(enemy_dic_x[enemy])), int(mean(enemy_dic_y[enemy])))] = (0,0,0,255)
            # large_image.putpixel((int(mean(enemy_dic_x[enemy])),int(mean(enemy_dic_y[enemy]))), (0, 0, 0))

        for m_team in team_dic_x:
            new_my_team.append((int(mean(team_dic_x[m_team])), int(mean(team_dic_y[m_team]))))
            # img_array[(int(mean(team_dic_x[m_team])), int(mean(team_dic_y[m_team])))] = (100, 100, 100,255)
            # large_image.putpixel((int(mean(team_dic_x[m_team])),int(mean(team_dic_y[m_team]))), (0, 0, 0))
        ball_position = []
        if ball_y_list:
            ball_position = (int(mean(ball_x_list)), int(mean(ball_y_list)))
            # large_image.putpixel((ball_position[0], ball_position[1]), (0, 0, 0))
        # print('after second data analyse = ', timezone.localtime() - loop_start_time)
        # if ball_position and len(new_my_team) < 11 and len(new_enemy_team) < 11:
        #     large_image.save(f'minimap/{minimap_counter}_converted_tmp.png')
        # if len(new_my_team) > 11 or len(new_enemy_team) > 11:
        #     large_image.save(f'minimap/{minimap_counter}_more_tmp.png')
        # print('minimap counter =', minimap_counter, 'my_team len', len(my_team_positions), 'enemy_team len',
        #       len(enemy_team_positions))
        # print('my team', new_my_team)
        # print('enemy team', new_enemy_team)
        # large_image.save(f'minimap/{minimap_counter}_converted_tmp.png')
        # im.save(f'minimap/{minimap_counter}_tmp.png')
        return {
            'ball': ball_position,
            'my_team': new_my_team,
            'enemy_team': new_enemy_team,
            'map': large_image
        }

    def update_minimap_data(self):
        # last_time = timezone.localtime()
        counter = 0
        while True:
            counter += 1
            # new_time = timezone.localtime()
            # print('one loop time = ',str(new_time - last_time))
            # last_time = new_time
            self.minimap_data = self.read_minimap_data(minimap_counter=counter)
            if self.break_get_minimap_data:
                break
            if (self.minimap_data['ball'] and
                    len(self.minimap_data.get('my_team', [])) > 5 and
                    len(self.minimap_data.get('enemy_team', [])) > 5
            ):
                self.map = True
                self.ps4_buttons.press_cross(press_time=0.001)
            else:
                self.map = False

    def get_ball_position(self):
        large_image_name = self.get_screen_from_minimap()

        # large_image = Image.open('minimap_screenshot_tmp.png')
        large_image = Image.open(large_image_name)
        width, height = large_image.size
        pixels = large_image.load()
        for x in range(width):
            for y in range(height):
                current_pixel = pixels[x, y]
                if (
                        current_pixel[0] in range(210, 260) and
                        current_pixel[1] in range(135, 195) and
                        current_pixel[2] in range(0, 45)
                ):
                    return (x, y)

    def get_screen_from_minimap(self, try_counter=0, minimap_counter=0, return_pic=False):
        if try_counter > 10:
            raise Exception('minimap screen shot Permission denied')
        try:
            snapshot = ImageGrab.grab(
                bbox=(*self.map_position.get('left_top'), *self.map_position.get('right_button')))
            if return_pic:
                return snapshot
            else:
                save_path = 'minimap_screenshot_tmp.png'
                snapshot.save(save_path)
                # snapshot.save(f'minimap/{minimap_counter}_tmp.png')
                return save_path
        except PermissionError:
            new_print(self.fifa_account, 'get_screen_from_minimap try : ', try_counter, ' --- ', traceback.format_exc())
            return self.get_screen_from_minimap(try_counter=try_counter + 1)

    def start_opponent(self, countdown=0, special_game_one=False, special_game_two=False):
        new_print(self.fifa_account, 'selecting opponent .... ')
        if special_game_one:
            [self.ps4_buttons.up(sleep_after=.5) for nc in range(3)]
            [self.ps4_buttons.left(sleep_after=.5) for nc in range(3)]
            new_print(self.fifa_account, 'special game one selected ')
            return
        if special_game_two:
            [self.ps4_buttons.up(sleep_after=.5) for nc in range(3)]
            [self.ps4_buttons.right(sleep_after=.5) for nc in range(3)]
            new_print(self.fifa_account, 'special game two selected ')
            return
        for nt in range(3):
            self.ps4_buttons.left()
            self.ps4_buttons.down()
        has_game = 0
        for i in [self.ps4_buttons.right, self.ps4_buttons.up, self.ps4_buttons.left, self.ps4_buttons.left]:
            time.sleep(1)
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/select_squad_game_button.png'),
                    'screen_shot_tmp.jpg'):
                has_game = 1
                break
            else:
                i()
        self.public_moves.get_screen_shot()
        if has_game == 0:
            new_print(self.fifa_account, 'no game left , refresh squad games')
            self.ps4_buttons.square()
            time.sleep(1)
        else:
            return
        if countdown > 5:
            new_print(self.fifa_account, 'can not refresh opponent without loss, loss one opponent')
            self.ps4_buttons.right()
            self.ps4_buttons.cross()
            return
        if self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/refresh_opponents.png'),
                'screen_shot_tmp.jpg'):
            self.ps4_buttons.circle()
            time.sleep(1)
            return self.start_opponent(countdown + 1)

    def start_opponent_2(self, countdown=0):
        new_print(self.fifa_account, 'selecting opponent 2.... ')
        if countdown > 1:
            return ['can not find good opponent', None]
        for nt in range(3):
            self.ps4_buttons.left()
            self.ps4_buttons.down()
        for i in [self.ps4_buttons.right, self.ps4_buttons.up, self.ps4_buttons.left, self.ps4_buttons.left]:
            time.sleep(1)
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/select_squad_game_button.png'),
                    'screen_shot_tmp.jpg'):
                current_opponent_rating = self.get_opponent_rating()
                # if current_opponent_rating and 50 < current_opponent_rating <= 70:
                #     difficulty_name = 'professional'
                #     return [difficulty_name, current_opponent_rating]
                # elif current_opponent_rating and 70 < current_opponent_rating <= 85:
                #     difficulty_name = 'semi_pro'
                #     return [difficulty_name, current_opponent_rating]
                if current_opponent_rating and 45 < current_opponent_rating <= 72:
                    difficulty_name = 'semi_pro'
                    return [difficulty_name, current_opponent_rating]
                else:
                    i()
            else:
                i()
        new_print(self.fifa_account, 'no good game left , refresh squad games')
        self.ps4_buttons.square()
        time.sleep(1)
        self.public_moves.get_screen_shot()
        if self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/refresh_opponents.png'),
                'screen_shot_tmp.jpg'):
            self.ps4_buttons.right(sleep_after=.5)
            self.ps4_buttons.cross(sleep_after=5)
        return self.start_opponent_2(countdown=countdown + 1)

    def get_opponent_rating(self):
        img = cv2.imread("screen_shot_tmp.jpg")
        # this position is static based on xboxs and monitor 1920 * 1080
        crop_team_name = img[320:350, 790:835]
        # crop_player_name = cv2.cvtColor(crop_player_name, cv2.COLOR_BGR2GRAY)
        cv2.imwrite('crop_team_rate_tmp.jpg', crop_team_name)
        # team_rate = self.get_screen_text('crop_team_rate.jpg', convert=True)
        team_rate = self.public_moves.screen_utils.get_screen_text(
            'crop_team_rate_tmp.jpg',
            config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789',
            convert=True)
        try:
            return int(team_rate)
        except:
            return

    def get_second_behindest(self, points_list, round_number):
        if round_number == 1:
            behind_point = [400, 400]
            second_behind = [400, 400]
            for point in points_list:
                if point[0] < behind_point[0]:
                    behind_point = point
            for point in points_list:
                if point[0] < second_behind[0] and point != behind_point:
                    second_behind = point
        else:
            behind_point = [0, 0]
            second_behind = [0, 0]
            for point in points_list:
                if point[0] > behind_point[0]:
                    behind_point = point
            for point in points_list:
                if point[0] > second_behind[0] and point != behind_point:
                    second_behind = point
        return second_behind

    def get_frontest(self, points_list, round_number):
        if round_number == 1:
            front_point = [0, 0]
            for point in points_list:
                if point[0] > front_point[0]:
                    front_point = point
        else:
            front_point = [400, 400]
            for point in points_list:
                if point[0] < front_point[0]:
                    front_point = point
        return front_point

    def long_pass(self, minimap_data, distance_with_defence):
        frontest_target = self.get_frontest(minimap_data.get('my_team'), self.round)
        frontest_target_real = frontest_target
        l1_r1 = True
        if abs(frontest_target[0] - minimap_data.get('ball')[0]) < 2000:
            l1_r1 = False
            if self.round == 1:
                frontest_target = (frontest_target[0] + 10, frontest_target[1])
            else:
                frontest_target = (frontest_target[0] - 10, frontest_target[1])
        pass_compass = self.calculate_initial_compass_bearing(minimap_data.get('ball'),
                                                              frontest_target)
        # print('long pass compass : ', pass_compass)
        friend_x_num, friend_y_num = self.get_xbox_x_y_with_compass(pass_compass, float_xy=True)
        # print('long pass to compass ', friend_x_num, friend_y_num)
        press_time = 0.1
        if distance_with_defence < 8:
            press_time = 0.01

        self.ps4_buttons.press_left_joystick_float(friend_x_num, friend_y_num, press_time=press_time)
        self.ps4_buttons.l1()
        self.ps4_buttons.press_left_joystick_float(friend_x_num, friend_y_num, press_time=press_time)
        if l1_r1:
            self.ps4_buttons.press_r1(press_time=0)
            self.ps4_buttons.press_l1()
        self.ps4_buttons.release_r1(sleep_after=.01)
        self.ps4_buttons.triangle()
        self.ps4_buttons.press_r1()
        if l1_r1:
            self.ps4_buttons.release_l1()
        self.ps4_buttons.press_left_joystick_float(friend_x_num, friend_y_num, press_time=0.2)
        self.ps4_buttons.press_r2(sleep_after=0)
        self.r2_status = 1
        if self.round == 1:
            self.ps4_buttons.press_left_joystick_float(1, 0, press_time=0.01)
        else:
            self.ps4_buttons.press_left_joystick_float(-1, 0, press_time=0.01)
        sleep_time = 1.1
        if (self.round == 1 and frontest_target_real[0] >= 195) or (self.round == 2 and frontest_target_real[0] <= 65):
            sleep_time = 0.1
        time.sleep(sleep_time)

    # def play_untill_end_process(self):
    #     new_print(self.fifa_account, 'need to do play a game')
    #     self.public_moves.go_to_state('delete_club', 'squad_battles')
    #
    #     # self.public_moves.go_to_state('play_main', 'squad_battles')
    #     # self.ps4_buttons.cross()
    #     time.sleep(7)
    #     while True:
    #         self.public_moves.get_screen_shot()
    #         if self.public_moves.has_image(os.path.join(
    #                 BASE_DIR,
    #                 f'utils/{self.fifa_account.platform}_controls/advance.png'), 'screen_shot_tmp.jpg'):
    #             new_print(self.fifa_account, 'advanced form')
    #             self.ps4_buttons.cross()
    #             time.sleep(5)
    #         else:
    #             break
    #
    #     new_print(self.fifa_account, 'self.fifa_account.account_played_games = ',
    #               self.fifa_account.account_played_games)
    #     if self.fifa_account.account_played_games > 0:
    #         fix_pos = self.fifa_account.account_played_games % 4
    #         new_print(self.fifa_account, 'fix_pos = ', fix_pos)
    #         if fix_pos == 2:
    #             self.ps4_buttons.right()
    #         elif fix_pos == 3:
    #             self.ps4_buttons.right()
    #             self.ps4_buttons.down()
    #     while self.fifa_account.account_played_games < 10:
    #         self.set_sub_log('start playing %s' % self.fifa_account.account_played_games)
    #         self.do_special_move(self.fifa_account.account_played_games)
    #         count = 0
    #         difficulty_set = False
    #         success = False
    #         while count < 120:
    #             self.public_moves.get_screen_shot()
    #             if self.public_moves.has_image(os.path.join(
    #                     BASE_DIR,
    #                     f'utils/{self.fifa_account.platform}_controls/injured_or_contracts.png'),
    #                     'screen_shot_tmp.jpg'
    #             ) or self.public_moves.has_image(os.path.join(
    #                 BASE_DIR,
    #                 f'utils/{self.fifa_account.platform}_controls/manager_contract.png'),
    #                 'screen_shot_tmp.jpg'
    #             ) or self.public_moves.has_image(os.path.join(
    #                 BASE_DIR,
    #                 f'utils/{self.fifa_account.platform}_controls/concept_error.png'),
    #                 'screen_shot_tmp.jpg'
    #             ):
    #                 new_print(self.fifa_account, 'injured_or_contracts or Concept error')
    #                 self.ps4_buttons.down()
    #                 time.sleep(1)
    #                 self.ps4_buttons.cross()
    #                 time.sleep(2)
    #                 self.ps4_buttons.circle()
    #                 time.sleep(2)
    #                 self.ps4_buttons.circle()
    #                 time.sleep(5)
    #                 self.ps4_buttons.circle()
    #                 self.sbc_worker.refresh_from_db()
    #                 self.sbc_worker.main_squad = False
    #                 self.sbc_worker.save()
    #                 new_print(self.fifa_account, 'need to reset 1')
    #                 self.public_moves.go_to_state('squad_battles', 'play_main')
    #                 new_print(self.fifa_account, 'need to reset active squad')
    #                 raise 'need to reset active squad'
    #
    #             if count == 5:
    #                 if self.public_moves.has_image(os.path.join(
    #                         BASE_DIR,
    #                         f'utils/{self.fifa_account.platform}_controls/opponent_select.png'),
    #                         'screen_shot_tmp.jpg'):
    #                     self.ps4_buttons.square()
    #                     self.public_moves.get_screen_shot()
    #                     if self.public_moves.has_image(os.path.join(
    #                             BASE_DIR,
    #                             f'utils/{self.fifa_account.platform}_controls/refresh_opponents.png'),
    #                             'screen_shot_tmp.jpg'):
    #                         self.ps4_buttons.right()
    #                         self.ps4_buttons.cross()
    #                     time.sleep(10)
    #                     count = 0
    #                     for i in range(5):
    #                         self.ps4_buttons.up()
    #                     self.ps4_buttons.down()
    #             if not difficulty_set:
    #                 new_print(self.fifa_account, 'inside difficulty check')
    #                 time.sleep(2)
    #                 self.public_moves.get_screen_shot()
    #                 if self.public_moves.has_image(os.path.join(
    #                         BASE_DIR,
    #                         f'utils/{self.fifa_account.platform}_controls/squad_battle_go_to_game.png'),
    #                         'screen_shot_tmp.jpg'):
    #                     new_print(self.fifa_account, 'difficulty select founded')
    #                     time.sleep(1)
    #                     while True:
    #                         self.public_moves.get_screen_shot()
    #                         if self.public_moves.has_image(os.path.join(
    #                                 BASE_DIR,
    #                                 f'utils/{self.fifa_account.platform}_controls/beginner_difficulty.png'),
    #                                 'screen_shot_tmp.jpg'):
    #                             new_print(self.fifa_account, 'difficulty is set')
    #                             break
    #                         else:
    #                             new_print(self.fifa_account, 'couldnt see the difiiculty')
    #                             self.ps4_buttons.up()
    #                             time.sleep(1)
    #                     difficulty_set = True
    #                     self.ps4_buttons.cross()
    #                     self.wait_for_image(
    #                         os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/squad_in_game.png'))
    #                     time.sleep(2)
    #                     continue
    #             new_print(self.fifa_account, 'press cross')
    #             self.ps4_buttons.cross()
    #             if self.public_moves.has_image(
    #                     os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/scoreboard.png'),
    #                     'screen_shot_tmp.jpg'
    #             ):
    #                 success = True
    #                 break
    #             time.sleep(1)
    #             count += 1
    #         if success:
    #             need_to_continue = False
    #             while True:
    #                 do_sp = False
    #                 if need_to_continue:
    #                     do_sp = True
    #                 need_to_continue = False
    #                 # if self.fifa_account.account_played_games == 0:
    #                 if True:
    #                     self.ps4_buttons.option()
    #                     time.sleep(2.5)
    #                     if do_sp:
    #                         for i in range(10):
    #                             self.ps4_buttons.left()
    #                             time.sleep(0.5)
    #                         self.ps4_buttons.right()
    #                         time.sleep(0.5)
    #                     self.ps4_buttons.down()
    #                     time.sleep(1)
    #                     self.ps4_buttons.down()
    #                     time.sleep(1)
    #                     # self.ps4_buttons.right()
    #                     self.ps4_buttons.cross()
    #                     time.sleep(3)
    #                     self.ps4_buttons.right()
    #                     time.sleep(1)
    #                     self.ps4_buttons.cross()
    #                     time.sleep(3)
    #                     self.ps4_buttons.r2()
    #                     time.sleep(2)
    #                     count = 0
    #                     while True:
    #                         count += 1
    #                         if count > 40:
    #                             need_to_continue = True
    #                             break
    #                         self.public_moves.get_screen_shot()
    #                         if self.public_moves.has_image(
    #                                 os.path.join(BASE_DIR,
    #                                              f'utils/{self.fifa_account.platform}_controls/user_radar.png'),
    #                                 'screen_shot_tmp.jpg'):
    #                             break
    #                         self.ps4_buttons.down()
    #                         time.sleep(0.5)
    #                     if need_to_continue:
    #                         for i in range(10):
    #                             self.ps4_buttons.circle()
    #                         continue
    #                     count = 0
    #                     while True:
    #                         count += 1
    #                         if count > 40:
    #                             need_to_continue = True
    #                             break
    #                         self.public_moves.get_screen_shot()
    #                         if self.public_moves.has_image(
    #                                 os.path.join(BASE_DIR,
    #                                              f'utils/{self.fifa_account.platform}_controls/radar_red.png'),
    #                                 'screen_shot_tmp.jpg'):
    #                             break
    #                         self.ps4_buttons.right()
    #                         time.sleep(0.5)
    #                     if need_to_continue:
    #                         for i in range(10):
    #                             self.ps4_buttons.circle()
    #                         continue
    #                     count = 0
    #                     while True:
    #                         count += 1
    #                         if count > 40:
    #                             need_to_continue = True
    #                             break
    #                         self.public_moves.get_screen_shot()
    #                         if self.public_moves.has_image(os.path.join(
    #                                 BASE_DIR,
    #                                 f'utils/{self.fifa_account.platform}_controls/opponent_radar.png'),
    #                                 'screen_shot_tmp.jpg'):
    #                             break
    #                         self.ps4_buttons.down()
    #                         time.sleep(0.5)
    #                     if need_to_continue:
    #                         for i in range(10):
    #                             self.ps4_buttons.circle()
    #                         continue
    #                     count = 0
    #                     while True:
    #                         count += 1
    #                         if count > 40:
    #                             need_to_continue = True
    #                             break
    #                         self.public_moves.get_screen_shot()
    #                         if self.public_moves.has_image(
    #                                 os.path.join(BASE_DIR,
    #                                              f'utils/{self.fifa_account.platform}_controls/radar_blue.png'),
    #                                 'screen_shot_tmp.jpg'
    #                         ):
    #                             break
    #                         self.ps4_buttons.right()
    #                         time.sleep(0.5)
    #                     if need_to_continue:
    #                         for i in range(10):
    #                             self.ps4_buttons.circle()
    #                         continue
    #                     self.ps4_buttons.circle()
    #                     time.sleep(1)
    #                     self.ps4_buttons.circle()
    #                     time.sleep(2)
    #                     self.ps4_buttons.circle()
    #                     time.sleep(1)
    #                     self.ps4_buttons.circle()
    #                     break
    #
    #             for i in range(2):
    #                 count = 0
    #                 while True:
    #                     count += 1
    #                     if count > 40:
    #                         new_print(self.fifa_account, 'cant get round number')
    #                         self.put_on_rest_mode()
    #                         raise 'need to reloop for play'
    #                     round_number = self.get_round_number()
    #                     if round_number:
    #                         break
    #                     time.sleep(1)
    #                 self.round = round_number
    #                 self.break_press_r1 = False
    #                 new_print(self.fifa_account, 'start playing')
    #                 self.start_playing()
    #                 new_print(self.fifa_account, 'end of playing')
    #                 self.break_press_r1 = True
    #                 self.ps4_buttons.cross()
    #                 time.sleep(2)
    #                 self.ps4_buttons.cross()
    #             count = 0
    #             while True:
    #                 count += 1
    #                 if count > 40:
    #                     new_print(self.fifa_account, 'cant get opponent select')
    #                     self.put_on_rest_mode()
    #                     raise 'need to reloop for play'
    #                 self.public_moves.get_screen_shot()
    #                 if self.public_moves.has_image(os.path.join(
    #                         BASE_DIR,
    #                         f'utils/{self.fifa_account.platform}_controls/opponent_select.png'),
    #                         'screen_shot_tmp.jpg'):
    #                     break
    #                 self.ps4_buttons.cross()
    #                 time.sleep(1)
    #
    #             # self.wait_for_image(os.path.join(BASE_DIR, 'utils/controls/opponent_select.png'))
    #
    #             self.fifa_account.account_played_games += 1
    #             self.fifa_account.save(update_fields=['account_played_games'])
    #             self.fifa_account.refresh_from_db()
    #             new_print(self.fifa_account, 'number of account_played_games = ',
    #                       self.fifa_account.account_played_games)
    #             if self.fifa_account.account_played_games == 4 or self.fifa_account.account_played_games == 8:
    #                 time.sleep(10)
    #                 self.ps4_buttons.square()
    #                 self.public_moves.get_screen_shot()
    #                 if self.public_moves.has_image(os.path.join(
    #                         BASE_DIR,
    #                         f'utils/{self.fifa_account.platform}_controls/refresh_opponents.png'),
    #                         'screen_shot_tmp.jpg'):
    #                     self.ps4_buttons.right()
    #                     self.ps4_buttons.cross()
    #                 time.sleep(10)
    #                 for i in range(5):
    #                     self.ps4_buttons.up()
    #                 self.ps4_buttons.down()
    #             self.set_sub_log('end of play %s' % (self.fifa_account.account_played_games - 1))
    #         else:
    #             new_print(self.fifa_account, 'failed in playing for loyal')
    #             return False
    #     self.ps4_buttons.circle()
    #     time.sleep(1)
    #     self.fifa_account.refresh_from_db()
    #     self.sbc_worker.refresh_from_db()
    #     if self.fifa_account.account_played_games >= 10 and self.sbc_worker.loyal_played_numbers < 10:
    #         self.sbc_worker.main_squad = False
    #         self.sbc_worker.save()
    #     return True

    def select_game_setting(self, image_1, image_2):
        count = 0
        while True:
            count += 1
            if count > 100:
                return False
            self.public_moves.get_screen_shot()
            img = cv2.imread("screen_shot_tmp.jpg")
            crop_team_name = img[1:1000, 1:1000]
            cv2.imwrite('crop_game_settings_tmp.jpg', crop_team_name)
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_game_settings/{image_1}'),
                    'crop_game_settings_tmp.jpg'):
                break
            self.ps4_buttons.down()
            time.sleep(0.5)
        count = 0
        while True:
            count += 1
            if count > 10:
                return False
            self.public_moves.get_screen_shot()
            img = cv2.imread("screen_shot_tmp.jpg")
            crop_team_name = img[1:1000, 1:1000]
            cv2.imwrite('crop_game_settings_tmp.jpg', crop_team_name)
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_game_settings/{image_2}'),
                    'crop_game_settings_tmp.jpg'):
                break
            self.ps4_buttons.right()
            time.sleep(0.5)
        return True

    def set_squad_game_settings(self):
        while True:
            self.ps4_buttons.option()
            time.sleep(2.5)
            for i in range(5):
                self.ps4_buttons.down()
                time.sleep(1)
            self.ps4_buttons.cross()
            time.sleep(3)
            self.ps4_buttons.cross()
            time.sleep(3)
            new_print(self.fifa_account, 'i must be in game setting')
            select_option = self.select_game_setting('defending_select.png', 'defending_option.png')
            if not select_option:
                for i in range(10):
                    self.ps4_buttons.circle()
                continue
            select_option = self.select_game_setting(
                'auto_swiching_move_assistant_select.png',
                'auto_swiching_move_assistant_option.png')
            if not select_option:
                for i in range(10):
                    self.ps4_buttons.circle()
                continue
            select_option = self.select_game_setting(
                'auto_player_switching_select.png',
                'auto_player_switching_option.png')
            if not select_option:
                for i in range(10):
                    self.ps4_buttons.circle()
                continue
            self.ps4_buttons.r1()
            time.sleep(1)
            self.ps4_buttons.r1()
            time.sleep(2)
            select_option = self.select_game_setting('user_radar.png', 'radar_red.png')
            if not select_option:
                for i in range(10):
                    self.ps4_buttons.circle()
                continue
            select_option = self.select_game_setting('opponent_radar.png', 'radar_blue.png')
            if not select_option:
                for i in range(10):
                    self.ps4_buttons.circle()
                continue
            self.ps4_buttons.circle()
            time.sleep(1)
            self.ps4_buttons.circle()
            time.sleep(2)
            self.ps4_buttons.circle()
            time.sleep(1)
            self.ps4_buttons.circle()
            time.sleep(5)
            set_sub_log(self.sbc_worker, 'end of setting settings ...')
            break

    def get_round_number(self):
        # large_image_name = self.get_screen_from_minimap()
        # large_image = Image.open(large_image_name)
        # large_image = Image.open('minimap_screenshot_tmp.png')
        large_image = self.get_screen_from_minimap(return_pic=True)

        width, height = large_image.size
        pixels = large_image.load()
        first_point = None
        last_point = None
        for x in range(width):
            for y in range(height):
                current_pixel = pixels[x, y]
                if (
                        current_pixel[0] in range(190, 260) and
                        current_pixel[1] in range(0, 45) and
                        current_pixel[2] in range(0, 45)
                ):
                    if x < int(0.269 * self.map_position['width']):
                        # we are in left side
                        if first_point is None:
                            first_point = x
                        last_point = x
                        # return 1
                    if x > int(0.692 * self.map_position['width']):
                        # we are in right side
                        if first_point is None:
                            first_point = x
                        last_point = x
                        # return 2
        if first_point and first_point < int(0.269 * self.map_position['width']) and last_point > int(0.692 * self.map_position['width']):
            # can not find ball
            return 0
        elif first_point and first_point < int(0.269 * self.map_position['width']):
            # we are in left side
            return 1
        elif first_point and first_point > int(0.692 * self.map_position['width']):
            # we are in right side
            return 2
        return 0

    def passing_best_player(self, ball, my_team, enemy_team, round_number):
        front_players = []
        good_players = []
        best_player = None
        if (round_number == 1 and ball[0] > int(0.353 * self.map_position['width'])) or (round_number == 2 and ball[0] < int(0.642 * self.map_position['width'])):
            return best_player
        for item in my_team:
            # print(item,'-------')
            # print(item[0] , ball[0] , round_number)
            if ((item[0] < ball[0] and round_number == 2) or (item[0] > ball[0] and round_number == 1)) and (
                    abs(ball[0] - item[0]) + abs(ball[1] - item[1]) < 100):
                front_players.append(item)
        # print('ball= ',ball)
        # print('my_team = ',my_team)
        # print('front_players = ',front_players)
        if front_players:
            # print('nearest : ', self.get_nearest_point(ball, front_players))
            for item_2 in front_players:
                # print('front player : ', item_2)
                nearest_enemy = self.get_nearest_point(item_2, enemy_team)
                # print('item_2[0] : ',item_2)
                # print('nearest_enemy[0] : ',nearest_enemy)
                try:
                    if not (item_2[0] - 20 < nearest_enemy[0] < item_2[0] + 20 and
                            item_2[1] - 20 < nearest_enemy[1] < item_2[1] + 20):
                        # print('good player : ', item_2)
                        good_players.append(item_2)
                except:
                    pass
                # else:
                #     print(item_2,nearest_enemy)
        # print('good_players = ',good_players)
        if good_players:
            best_player = self.get_nearest_point(ball, good_players)
        # print('best player ', best_player , ' ball : ', ball , ' round : ',round_number)
        return best_player

    def move_best_direction(self, ball, my_team, enemy_team, round_number):
        # front_players = []
        # bad_enemies = []
        # bad_enemy = None
        # for item in enemy_team:
        #     # todo : in change round must change bellow
        #     if item[0] < ball[0]:
        #         front_players.append(item)
        # for item_2 in enemy_team:
        #     nearest_enemy = self.get_nearest_point(item_2, enemy_team)
        #     if (item_2[0] - 10 < nearest_enemy[0] < item_2[0] + 10 and
        #             item_2[1] - 10 < nearest_enemy[1] < item_2[1] + 10):
        #         print('enemy player : ', item_2)
        #         bad_enemies.append(item_2)
        # if bad_enemies:
        #     bad_enemy = get_nearest(ball, bad_enemies)
        # if bad_enemy:
        #     print('bad enemy')
        # print('bad enemy : ', bad_enemy)
        # print(calculate_initial_compass_bearing(ball,bad_enemy))
        if ball[1] < int(.485 * self.map_position['height']):
            goal_position = (0, int(0.462 * self.map_position['height'])) if round_number == 2 else (self.map_position['width'], int(0.462 * self.map_position['height']))
        else:
            goal_position = (0, int(0.5 * self.map_position['height'])) if round_number == 2 else (self.map_position['width'], int(0.5 * self.map_position['height']))
        goal_compass = self.calculate_initial_compass_bearing(ball, goal_position)
        if abs(ball[0] - goal_position[0]) < int(0.288 * self.map_position['width']):
            return [goal_compass]
        #     if round_number == 1:
        #         return [90]
        #     else:
        #         return [270]

        # print('goal compass is : ', goal_compass)
        # a = list(range(int(goal_compass), 180, -1))
        # b = list(range(int(goal_compass), 360, 1))
        # c = list(range(180, 90, -1))
        # d = list(range(0, 90, 1))
        if round_number == 1:
            a = list(range(int(goal_compass), 180, 1))
            b = list(range(int(goal_compass), 0, -1))
            # a = list(range(90, 180, 1))
            # b = list(range(90, 0, -1))
            c = list(range(180, 270, 1))
            d = list(range(360, 270, -1))
        elif round_number == 2:
            a = list(range(int(goal_compass), 180, -1))
            b = list(range(int(goal_compass), 360, 1))
            # a = list(range(270, 180, -1))
            # b = list(range(270, 360, 1))
            c = list(range(180, 90, -1))
            d = list(range(0, 90, 1))
        else:
            return [180]
        compass_list = a + b + c + d
        # if ball[0] > 80:
        #     compass_list = a + b + c + d
        # else:
        #     compass_list = b + a + c + d
        list_c = []
        # print('front players : ', front_players)
        min_distance = 1000
        for item3 in enemy_team:
            # print('item 3 : ', item3)
            enemy_compass = self.calculate_initial_compass_bearing(ball, item3)
            x_distance = abs(ball[0] - item3[0])
            y_distance = abs(ball[1] - item3[1])
            if min_distance > x_distance + y_distance:
                min_distance = x_distance + y_distance
            # print('enemy compass : ', enemy_compass)
            difference = abs(item3[0] - ball[0]) + abs(item3[1] - ball[1])
            if difference < 10:
                deg = 90
            elif difference < 20:
                deg = 60
            elif difference < 30:
                deg = 40
            else:
                deg = 20
            if difference < 40:
                list_c += list(range(int(enemy_compass) - deg, int(enemy_compass) + deg))
        # print(sorted(list_c))
        # print('list c : ', list_c)
        # if min_distance > 25:
        #     return [goal_compass]
        best_directions_list = [x for x in compass_list if x not in list_c]
        # print('best directions : ', best_directions_list)
        return best_directions_list

    def calculate_initial_compass_bearing(self, point_a, point_b):
        """
        Calculates the bearing between two points.
        The formulae used is the following:
            θ = atan2(sin(Δlong).cos(lat2),
                      cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong))
        :Parameters:
          - `point_a: The tuple representing the latitude/longitude for the
            first point. Latitude and longitude must be in decimal degrees
          - `point_b: The tuple representing the latitude/longitude for the
            second point. Latitude and longitude must be in decimal degrees
        :Returns:
          The bearing in degrees
        :Returns Type:
          float
        """
        if (type(point_a) not in [tuple, list]) or (type(point_b) not in [tuple, list]):
            raise TypeError("Only tuples are supported as arguments")

        deltaX = point_b[0] - point_a[0]

        deltaY = point_b[1] - point_a[1]
        degrees_temp = math.atan2(deltaX, deltaY) / math.pi * 180

        if degrees_temp < 0:

            degrees_final = 360 + degrees_temp

        else:

            degrees_final = degrees_temp

        return degrees_final

    def get_nearest_point(self, point, points_list):
        nearest = []
        for item in points_list:
            if nearest and (abs(point[0] - nearest[0]) + abs(point[1] - nearest[1])
            ) > (abs(point[0] - item[0]) + abs(point[1] - item[1])):
                nearest = item
            elif not nearest:
                nearest = item
        return nearest

    def shoot(self, minimap_data, power_shoot=False):
        # print('want to shoot',power_shoot, minimap_data.get('ball'))
        # for i in range(2):
        if minimap_data.get('ball')[1] < int(0.487 * self.map_position['height']):
            if self.round == 1:
                destination = (self.map_position['width'] - 3, int(0.437 * self.map_position['height']))
            else:
                destination = (3, int(0.437 * self.map_position['height']))
        else:
            if self.round == 1:
                destination = (self.map_position['width'] - 3, int(0.537 * self.map_position['height']))
            else:
                destination = (3, int(0.537 * self.map_position['height']))
        shoot_compass = self.calculate_initial_compass_bearing(minimap_data.get('ball'), destination)
        # print('long pass compass : ', shoot_compass)
        friend_x_num, friend_y_num = self.get_xbox_x_y_with_compass(shoot_compass, float_xy=True)
        # print('long pass to compass ', friend_x_num, friend_y_num)
        self.ps4_buttons.press_left_joystick_float(friend_x_num, friend_y_num, press_time=.01)
        press_time = 0.20
        if power_shoot:
            self.ps4_buttons.press_r1(press_time=0.01)
            self.ps4_buttons.press_l1()
            press_time = 0.25
        self.ps4_buttons.press_r1(press_time=0.01)
        if (int(0.173 * self.map_position['width'])
                <= minimap_data.get('ball')[0] <=
                int(0.826 * self.map_position['width'])):
            press_time = 0.20
        self.ps4_buttons.circle(press_time=press_time)

        if power_shoot:
            self.ps4_buttons.release_l1()
            # time.sleep(.5)

            # self.ps4_buttons.press_r1()
            # self.ps4_buttons.press_l1()
            # self.ps4_buttons.release_r1()
            # self.ps4_buttons.release_l1()

    def get_xbox_x_y_with_compass(self, compass, float_xy=False):
        new_compass = compass - 90
        if new_compass < 0:
            new_compass = new_compass + 360
        # print(new_compass)
        new_compass = int(new_compass)
        # print(new_compass)
        # print('cos ',math.cos(math.radians(new_compass)))
        # print('sin ',math.sin(math.radians(new_compass)))
        if float_xy:
            joystic_x = math.cos(math.radians(new_compass))
            joystic_y = math.sin(math.radians(new_compass))
            return joystic_x, joystic_y
        if self.fifa_account.platform in ['xbox', 'xboxs']:
            xbox_x = math.cos(math.radians(new_compass)) * 32767
            xbox_y = math.sin(math.radians(new_compass)) * 32767
        else:
            # todo : fix x and y in ps control
            xbox_x = math.cos(math.radians(new_compass)) * 32767
            xbox_y = math.sin(math.radians(new_compass)) * 32767
        # print(xbox_x)
        # print(xbox_y)
        return int(xbox_x), int(xbox_y)

    def do_special_move(self, counter):
        if counter % 4 == 0:
            pass
        elif counter % 4 == 1:
            self.ps4_buttons.right()
        elif counter % 4 == 2:
            self.ps4_buttons.down()
        elif counter % 4 == 3:
            self.ps4_buttons.left()

    def check_squad_errors(self):
        self.public_moves.get_screen_shot()
        need_something = False
        need_text = ''
        if self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/injured_or_contracts.png'),
                'screen_shot_tmp.jpg'
        ):
            new_print(self.fifa_account, 'injured or contract need')
            set_sub_log(self.sbc_worker, 'injured or contracts')
            heal_result = self.find_need_heal_player()
            if heal_result == 'not heal need':
                need_something = True
            elif heal_result == 'low heal':
                set_sub_log(self.sbc_worker, 'need heal. buy 5 heal')
                need_something = True
                need_text = 'low heal'
            elif heal_result == 'complete':
                set_sub_log(self.sbc_worker, 'heal used success')
                return 'continue'
        elif self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/manager_contract.png'),
                'screen_shot_tmp.jpg'
        ):
            set_sub_log(self.sbc_worker, 'manager contract need')
            new_print(self.fifa_account, 'manager contract need')
            need_something = True
        elif self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/players_banned.png'),
                'screen_shot_tmp.jpg'
        ):
            set_sub_log(self.sbc_worker, 'player ban in squad')
            new_print(self.fifa_account, 'player banned in squad')
            need_something = True
        elif self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/concept_error.png'),
                'screen_shot_tmp.jpg'
        ) or self.public_moves.has_image(os.path.join(
            BASE_DIR,
            f'utils/{self.fifa_account.platform}_controls/concept_error_2.png'),
            'screen_shot_tmp.jpg'
        ):
            set_sub_log(self.sbc_worker, 'concept error')
            new_print(self.fifa_account, 'concept squad not eligible to play match')
            need_something = True
        elif self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/empty_player_slots.png'),
                'screen_shot_tmp.jpg'
        ):
            set_sub_log(self.sbc_worker, 'empty player')
            new_print(self.fifa_account, 'you currently have less than the minimum required number of players')
            need_something = True
        elif self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/seassion_creation_error.png'),
                'screen_shot_tmp.jpg'
        ):
            set_sub_log(self.sbc_worker, 'session creation error')
            new_print(self.fifa_account, 'session creation error')
            need_something = True
        elif self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/player_expire_error.png'),
                'screen_shot_tmp.jpg'
        ):
            set_sub_log(self.sbc_worker, 'player expire error')
            new_print(self.fifa_account, 'player expire error')
            need_something = True
        elif self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/not_available_players.png'),
                'screen_shot_tmp.jpg'
        ):
            set_sub_log(self.sbc_worker, 'not_available_players error')
            new_print(self.fifa_account, 'not_available_players error')
            need_something = True
        elif self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/manager_bug.png'),
                'screen_shot_tmp.jpg'
        ):
            set_sub_log(self.sbc_worker, 'manager bug')
            set_sbc_status(self.sbc_worker, 'manager bug')
            new_print(self.fifa_account, 'manager buged')
            need_something = True
            need_text = 'need_change_manager'
        elif self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/squad_eligible.png'),
                'screen_shot_tmp.jpg'
        ):
            new_print(self.fifa_account, 'nothing need , go next')
            self.ps4_buttons.cross()
            time.sleep(1)
            self.ps4_buttons.option()
            time.sleep(2)
            return 'continue'
        if need_something:
            new_print(self.fifa_account, 'injured or contracts or Concept or empty player error')
            self.ps4_buttons.down()
            time.sleep(1)
            self.ps4_buttons.cross()
            time.sleep(2)
            self.ps4_buttons.circle()
            time.sleep(2)
            self.ps4_buttons.circle()
            time.sleep(5)
            self.ps4_buttons.circle()
            self.sbc_worker.main_squad = False
            self.sbc_worker.save(update_fields=['main_squad'])
            new_print(self.fifa_account, 'need to reset 1')
            self.public_moves.go_to_state('squad_battles', 'ultimate_team')
            new_print(self.fifa_account, 'need some things in active squad. going to prepare ...')
            if need_text:
                return need_text
            return 'need some things in active squad'

    def find_need_heal_player(self):
        self.ps4_buttons.cross()
        time.sleep(1)
        [self.ps4_buttons.up(sleep_after=.5) for nm in range(5)]
        [self.ps4_buttons.left(sleep_after=.5) for tt in range(3)]
        for i in range(5):
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(
                    # todo :  xbox360 image added. add ps and xboxs image
                    os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/band_aids.png'),
                    'screen_shot_tmp.jpg'):
                band_image_pos = get_image_position(
                    # todo :  xbox360 image added. add ps and xboxs image
                    os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/band_aids.png'),
                    'screen_shot_tmp.jpg')
                xbox_players_list = [
                    # (1,1,1,1) '(1,1' is image position , ',1' is down press , ',1)' is right press
                    (873 - 82, -1, 0), (1115 - 82, -1, 1),
                    (549 - 258, 0, 0), (846 - 285, 0, 1), (1142 - 285, 0, 2), (1449 - 258, 0, 3),
                    (549 - 489, 1, 0), (846 - 512, 1, 1), (1142 - 512, 1, 2), (1449 - 489, 1, 3),
                    (992 - 619, 2, 0)
                ]
                ps_players_list = [
                    # (1,1,1,1) '(1,1' is image position , ',1' is down press , ',1)' is right press
                    (709 - 149, -1, 0), (990 - 112, -1, 1), (1275 - 149, -1, 2),
                    (553 - 294, 0, 0), (851 - 308, 0, 1), (1134 - 307, 0, 3), (1440 - 294, 0, 5),
                    (686 - 434, 1, 0), (990 - 436, 1, 2), (1299 - 436, 1, 4),
                    (990 - 629, 2, 0)
                ]
                if self.fifa_account.platform in ['xbox360', 'xboxs']:
                    players_list = xbox_players_list
                else:
                    players_list = ps_players_list
                image_position = band_image_pos.get('top_left')
                image_position2 = image_position[0] - image_position[1]
                nearest = min(players_list, key=lambda x: abs(x[0] - image_position2))
                new_print(self.fifa_account, 'player card position : ', image_position, ' -- nearest : ', nearest)
                for nt in range(abs(nearest[1])):
                    if nearest[1] < 1:
                        self.ps4_buttons.up()
                    else:
                        self.ps4_buttons.down()
                    time.sleep(.5)
                for nt2 in range(nearest[2]):
                    self.ps4_buttons.right()
                    time.sleep(.5)

                self.ps4_buttons.square()
                time.sleep(5)
                self.public_moves.get_screen_shot()
                if not self.public_moves.has_image(os.path.join(
                        BASE_DIR,
                        # todo :  xbox360 image added. add ps and xboxs image
                        f'utils/{self.fifa_account.platform}_controls/consumble_heal_need_icon_2.png'),
                        'screen_shot_tmp.jpg'
                ):
                    new_print(self.fifa_account, 'this player not heal need')
                    self.ps4_buttons.circle()
                    time.sleep(2)
                    self.ps4_buttons.option()
                    time.sleep(2)
                    return 'not heal need'
                new_print(self.fifa_account, 'ok this player need heal')
                for nt3 in range(3):
                    self.public_moves.get_screen_shot()
                    if self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            # todo :  xbox360 image added. add ps and xboxs image
                            f'utils/{self.fifa_account.platform}_controls/consumble_heal_need_icon_2.png'),
                            'screen_shot_tmp.jpg'
                    ) and self.public_moves.has_image(os.path.join(
                        BASE_DIR,
                        # todo :  xbox360 image added. add ps and xboxs image
                        f'utils/{self.fifa_account.platform}_controls/consumble_search_icon.png'),
                        'screen_shot_tmp.jpg'
                    ):
                        new_print(self.fifa_account, 'low heal. need more')
                        self.ps4_buttons.circle()
                        time.sleep(1)
                        self.ps4_buttons.option()
                        time.sleep(2)
                        return 'low heal'
                    if self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            # todo :  xbox360 image added. add ps and xboxs image
                            f'utils/{self.fifa_account.platform}_controls/consumble_heal_need_icon.png'),
                            'screen_shot_tmp.jpg'
                    ):
                        new_print(self.fifa_account, 'player applied heal')
                        if self.fifa_account.platform in ['xboxs', 'xbox360']:
                            self.ps4_buttons.press_left_joystick(32000, -10000)
                            time.sleep(.5)
                            self.ps4_buttons.cross(press_time=1)
                            time.sleep(.5)
                            self.ps4_buttons.release_left_joystick()
                            time.sleep(4)
                        else:
                            self.ps4_buttons.press_left_joystick(250, 100)
                            time.sleep(.5)
                            self.ps4_buttons.cross(press_time=1)
                            time.sleep(.5)
                            self.ps4_buttons.release_left_joystick()
                            time.sleep(10)
                        time.sleep(1)

                self.ps4_buttons.circle()
                time.sleep(1)
                self.ps4_buttons.option()
                time.sleep(1)
                new_print(self.fifa_account, 'heal player was success and complete')
                return 'complete'
        return 'not heal need'

    def press_r1_continue(self):
        self.ps4_buttons.press_cross()
        counter = 0
        while self.break_press_r1 is False:
            counter += 1
            if counter % 10 == 0:
                self.ps4_buttons.release_r1()
                time.sleep(.5)
                self.ps4_buttons.press_r1()
            time.sleep(.5)
        self.ps4_buttons.release_r1()
        self.ps4_buttons.release_r2()
        self.r2_status = 0
        self.ps4_buttons.release_cross()
        self.ps4_buttons.release_left_joystick()

    def swap_injury_player(self, counter=0):
        if counter > 2:
            new_print(self.fifa_account, 'try to fix injure but can not fix it')
            return 'can not fix'
        self.ps4_buttons.reset_to_default()
        self.ps4_buttons.cross()
        time.sleep(1)
        for i in range(5):
            time.sleep(1)
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/injure_middle_game_1.png'),
                    'screen_shot_tmp.jpg'):
                new_print(self.fifa_account, 'ok i am in searching injure player')
                break
            self.ps4_buttons.l1()
        [self.ps4_buttons.up() for i in range(5)]
        [self.ps4_buttons.left() for i in range(5)]
        # this code only work with formation 4-4-2 flat
        for nm in [2, 4, 4, 1]:
            for nt in range(nm):
                self.public_moves.get_screen_shot()
                if self.public_moves.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/ambulance_icon.png'),
                        'screen_shot_tmp.jpg'):
                    new_print(self.fifa_account, 'ambulance player selected')
                    self.ps4_buttons.cross()
                    time.sleep(1)
                    [self.ps4_buttons.down() for i in range(5)]
                    time.sleep(1)
                    # [self.ps4_buttons.right() for i in range(counter)]
                    [self.ps4_buttons.right() for i in range(random.randint(0, 3))]
                    time.sleep(1)
                    self.ps4_buttons.cross()
                    time.sleep(1)
                    for sm in range(3):
                        self.ps4_buttons.circle()
                        time.sleep(1)
                    self.public_moves.get_screen_shot()
                    if self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/injure_middle_game.png'),
                            'screen_shot_tmp.jpg'):
                        new_print(self.fifa_account)
                        return self.swap_injury_player(counter=counter + 1)
                    else:
                        self.ps4_buttons.circle()
                        time.sleep(1)
                        self.ps4_buttons.circle()
                        return
                elif nt < (nm - 1):
                    new_print(self.fifa_account, f'current not ambulance : {nm} {nt}')
                    self.ps4_buttons.right()
                    time.sleep(1)
            for i in range(nm - 1):
                self.ps4_buttons.left()
                time.sleep(.5)
            self.ps4_buttons.down()
            time.sleep(1)
            if nm == 1:  # this is special for goaler
                self.ps4_buttons.down()
                time.sleep(1)
            self.ps4_buttons.left()
            time.sleep(1)
        self.ps4_buttons.circle()
        return self.swap_injury_player(counter=counter + 1)
