import os.path
import os.path
import random
import time
import traceback
import cv2
import pytesseract
import requests
from django.db import close_old_connections
from django.utils import timezone


from accounts.console_accounts_utils import ConsoleAccountsUtils
from accounts.models import FifaAccountSearch, PlayerCard
from squad_battle.models import FifaAccountSquadGame, FifaAccountMomentsGame
from futplus.settings import BASE_DIR, TIME_ZONE
from sbc import ARZBAZI_REPORT_TOPIC_DISCHARGE_ERROR_THREAD_MESSAGE_ID, ARZBAZI_REPORT_TOPIC_PLAYERS_NOT_FOUND_THREAD_MESSAGE_ID
from sbc.models import SBCWorker, SBCTargetFilter, SBCTargetFilterClubMoves, \
    SBCTargetFilterLeagueMoves, SBCTargetFilterNationMoves
from sbc.public_methods import new_print, get_previous_price_grade, get_next_price_grade, \
    has_image, set_main_log, set_sub_log, \
    get_image_position, get_player_data_by_asset_id, set_sbc_status, telegram_send_photo
from accounts.web_login_utils import logout_login
from utils.console_error_utils import ConsoleErrorUtils
from utils.console_login_utils import ConsoleLoginUtils
from utils.menu_utils import MenuUtils
from utils.play_footbal_utils import PlayFootballUtils
from utils.realy_public_methods import get_db_time
from utils.screen_utils import ScreenUtils
from utils.transfer_list_utils import TransferListUtils

if os.name == 'nt':
    from sbc.visual_buttons import PS4_Buttons, Uniqe_XBOXS_Buttons

from utils.graph_core import ps4_graph, xbox360_graph

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"


class PublicMoves:
    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, sbc_solver_instance, sbc_worker: SBCWorker, se: requests.Session, main_dic: dict, server_key):
        from sbc.sbc_solver import SBCSolver
        self.sbc_worker = sbc_worker
        self.fifa_account = sbc_worker.fifa_account
        self.se = se
        self.main_dic = main_dic
        self.server_key = server_key
        self.sbc_solver_instance: SBCSolver = sbc_solver_instance
        self.current_letter_pos = [0, 0]
        # new_print(self.fifa_account,'find path :',find_path(all_menus_dict, 'home_main', 'transfers'))
        # new_print(self.fifa_account,get_path(all_menus_dict, 'stadium_club', 'transfers'))
        # self.map_path(self.all_menus_dict, 'stadium_club', 'transfers')
        if self.fifa_account.platform in ['ps', 'ps5']:
            self.ps4_buttons = PS4_Buttons()
        elif self.fifa_account.platform in ['xboxs', 'xbox360']:
            # self.ps4_buttons = XBOXS_Buttons()
            self.ps4_buttons = Uniqe_XBOXS_Buttons()
        else:
            raise Exception('No Joystick Found')
        # new_print(self.fifa_account, 'joystick created. id is : ', self.ps4_buttons)


        self.keyboard = {'a': [0, 0], 'b': [0, 1], 'c': [0, 2], 'd': [0, 3], 'e': [0, 4], 'f': [0, 5],
                         'g': [0, 6], 'h': [0, 7], 'i': [0, 8], 'j': [0, 9], 'k': [0, 10], 'l': [0, 11], 'm': [0, 12],
                         'n': [1, 0], 'o': [1, 1], 'p': [1, 2], 'q': [1, 3], 'r': [1, 4], 's': [1, 5],
                         't': [1, 6], 'u': [1, 7], 'v': [1, 8], 'w': [1, 9], 'x': [1, 10], 'y': [1, 11], 'z': [1, 12]}

        self.break_press_r1 = False
        self.break_get_minimap_data = False
        self.map = False
        self.minimap_data = {}
        self.round = 3
        self.ball_position_x = 0
        self.r2_status = 0
        self.l2_status = 0
        self.duplicate_key_counter = 0
        self.cant_find_console_counter = 0
        self.set_account_suspend = True
        self.ea_connecting_wait = 0
        self.can_not_find_game = 0

        self.cant_buy_item_counter = 0

        self.image_cache = {}
        self.console_accounts_utils = ConsoleAccountsUtils(public_moves_instance=self)
        self.screen_utils = ScreenUtils(public_moves_instance=self)
        self.menu_utils = MenuUtils(public_moves_instance=self)
        if self.fifa_account.platform in ['ps', 'ps5']:
            self.menus = self.menu_utils.get_all_menus(ps4_graph)
        elif self.fifa_account.platform in ['xbox360', 'xboxs']:
            self.menus = self.menu_utils.get_all_menus(xbox360_graph)
        else:
            raise Exception('No Platform Found')
        self.all_menus_dict = self.menu_utils.make_menu_dict(self.menus)
        self.menu_utils.load_all_templates()
        self.console_error_utils = ConsoleErrorUtils(public_moves_instance=self)
        self.console_login_utils = ConsoleLoginUtils(public_moves_instance=self)
        self.transfer_list_utils = TransferListUtils(public_moves_instance=self)
        self.play_football_utils = PlayFootballUtils(public_moves_instance=self)

    # def find_path(menu: Menu, start, end, path=[], next_index=True):
    #     if start == end:
    #         new_print(self.fifa_account,'start === end')
    #         return
    #     if next_index:
    #         for node_item in menu.nodes:
    #             if node_item.name == start:
    #                 new_print(self.fifa_account,'start is ', node_item.name)
    #             if node_item.name == end:
    #                 new_print(self.fifa_account,'end = ', node_item.name)
    #                 path.append(node_item.name)
    #                 next_index = False
    #             if path:
    #                 path.append(node_item.name)
    #             find_path(node_item, start, end, path=path, next_index=next_index)
    #     return path

    def has_image(self, small_image_name, large_image_name, threshold=.9):
        return self.screen_utils.has_image(small_image_name, large_image_name, threshold=threshold)

    def get_screen_shot(self, image_name='screen_shot_tmp.jpg', try_counter=0):
        return self.screen_utils.get_screen_shot(image_name=image_name, try_counter=try_counter)

    def just_find_state(self, get_new_screen_shot=True):
        return self.menu_utils.just_find_state(get_new_screen_shot)

    def errors(self, excluded_images=None, add_log=True):
        return self.console_error_utils.errors(excluded_images, add_log)

    def close_game(self, try_counter=0, raise_error=True):
        return self.console_login_utils.close_game(try_counter=try_counter, raise_error=raise_error)

    def console_open_ultimate(self, have_to=False, state_set='ultimate_team', close_game=False):
        return self.console_login_utils.console_open_ultimate(have_to=have_to, state_set=state_set, close_game=close_game)

    def login_with_key(self, try_counter=0):
        return self.console_login_utils.login_with_key(try_counter=try_counter)

    def login_to_account(self, try_counter=0, special_error=None):
        return self.console_login_utils.login_to_account(try_counter=try_counter, special_error=special_error)

    def wait_for_image(self, small_image_name, large_image_name='screen_shot_tmp.jpg', wait_time=5, special='',
                       threshold=.9, excluded_errors_image=None, check_errors=True):
        if excluded_errors_image is None:
            excluded_errors_image = []
        new_print(self.fifa_account, 'wait for ', small_image_name)
        for i in range(wait_time + 2):
            self.get_screen_shot()
            if self.has_image(small_image_name, large_image_name, threshold=threshold):
                if not special == 'no_wait_after_find':
                    time.sleep(1)
                return True
            if special == 'live_search_results.png':
                if self.has_image(
                        os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/live_search_results.png'),
                        large_image_name
                ) or self.has_image(os.path.join(
                    BASE_DIR, f'utils/{self.fifa_account.platform}_controls/time_remaining.png'),
                    large_image_name):
                    return True

            if special == 'check_failed':
                if self.has_image(
                        os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/failed_action.png'),
                        large_image_name):
                    new_print(self.fifa_account, 'check failed 1 , failed happened. press cross and circle')
                    self.ps4_buttons.cross()
                    time.sleep(0.5)
                    self.ps4_buttons.circle()
                    time.sleep(1)
                    return False
            if check_errors and i > 1:
                self.errors(excluded_images=excluded_errors_image)
            time.sleep(1)
        return False

    def wait_for_images(self, small_image_list=None, large_image_name='screen_shot_tmp.jpg', wait_time=5, special='',
                        threshold=.9, excluded_errors_image=None, check_errors=True):
        if small_image_list is None:
            small_image_list = []
        if excluded_errors_image is None:
            excluded_errors_image = []
        new_print(self.fifa_account, 'wait for images : ', small_image_list, ' wait time : ', wait_time,
                  ' special : ', special, ' excluded_errors_image : ', excluded_errors_image,
                  ' check_errors : ', check_errors)
        for i in range(wait_time + 2):
            self.get_screen_shot()
            for small_image_name in small_image_list:
                if self.has_image(small_image_name, large_image_name, threshold=threshold):
                    if not special == 'no_wait_after_find':
                        time.sleep(1)
                    return True

            if special == 'live_search_results.png':
                if self.has_image(
                        os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/live_search_results.png'),
                        large_image_name) or self.has_image(
                    os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/time_remaining.png'),
                    large_image_name):
                    return True

            if special == 'check_failed':
                if self.has_image(
                        os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/failed_action.png'),
                        large_image_name):
                    new_print(self.fifa_account, 'check failed 2 , failed happened. press cross and circle')
                    self.ps4_buttons.cross()
                    time.sleep(0.5)
                    self.ps4_buttons.circle()
                    time.sleep(1)
                    return False
            if check_errors and i > 1:
                errors_result = self.errors(excluded_images=excluded_errors_image)
                if errors_result == 0 and special == 'find_state' and self.just_find_state(get_new_screen_shot=False):
                    return False
            time.sleep(1)
        return False

    def go_to_state(self, first_state, second_state, special_order=''):
        # new_print(self.fifa_account, 'joystick id is : ', self.ps4_buttons)
        if not self.menu_utils.control_state(first_state):
            new_print(self.fifa_account, 'need to find state',
                      ' first state ', first_state, ' second state ', second_state)
            first_state = self.menu_utils.find_state()
            new_print(self.fifa_account, 'state = ', first_state, ' second state = ', second_state)
        # if self.fifa_account.platform in ['xboxs', 'xbox360'] and first_state == 'ps4_main':
        #     new_print(self.fifa_account, 'need to 2 down press to find game groups')
        #     self.ps4_buttons.down()
        #     time.sleep(1)
        #     self.ps4_buttons.cross()

        the_path = self.menu_utils.map_path(self.all_menus_dict, first_state, second_state)
        # new_print(self.fifa_account, 'the_path = ', the_path)
        main_counter = 0
        while main_counter < len(the_path):

            main_counter_param_2 = the_path[main_counter][2]
            # for each_part in the_path:
            new_print(self.fifa_account, the_path[main_counter])
            # if (the_path[main_counter][1] == 'ultimate_team' and main_counter_param_2 == 'out') or \
            #         (the_path[main_counter][0] == 'ultimate_team' and the_path[main_counter][1] == 'home'):
            # if the_path[main_counter][1] == 'ultimate_team' and main_counter_param_2 == 'out':
            #     main_counter += 1
            #     continue
            if (self.fifa_account.platform in ['xboxs', 'xbox360'] and
                    the_path[main_counter][0] == 'ps4_main' and the_path[main_counter][1] == 'games_and_apps'):
                # for nm in range(10):
                #     self.ps4_buttons.left()
                # for nm in range(10):
                #     self.ps4_buttons.up()
                # self.ps4_buttons.down()
                # time.sleep(.5)
                # self.ps4_buttons.down()
                # time.sleep(1)
                # self.ps4_buttons.cross()
                # time.sleep(2)
                self.ps4_buttons.ps()
                time.sleep(1)
                self.ps4_buttons.down()
                time.sleep(1)
                self.ps4_buttons.cross()
                time.sleep(1)
                self.ps4_buttons.cross()
                time.sleep(2)
                main_counter += 1
                continue
            if (self.fifa_account.platform in ['xboxs', 'xbox360'] and
                    the_path[main_counter][1] == 'ps4_main' and the_path[main_counter][2] == 'out'):
                self.ps4_buttons.ps()
                time.sleep(1)
                self.ps4_buttons.cross()
                time.sleep(5)
                continue
            first_item = self.menu_utils.select_menu_items_by_name(the_path[main_counter][0])
            specials = first_item.specials
            first_multiple_images = [item_1.file_name for item_1 in first_item.multiple_images]

            second_item = self.menu_utils.select_menu_items_by_name(the_path[main_counter][1])
            second_specials = second_item.specials
            second_multiple_images = [item_1.file_name for item_1 in second_item.multiple_images]

            first_item_parent = ''
            for item in self.menus:
                if first_item in item.nodes:
                    first_item_parent = item
                    break
            parent_specials = []
            if first_item_parent:
                parent_specials = first_item_parent.specials

            need_right_left = 1
            if main_counter_param_2 != 'out':
                need_right_left = self.menu_utils.find_menu_icon(
                    need_right_left, specials, 'find_1', first_multiple_images,
                    use_r1_and_l1='use_r1_and_l1' in specials, use_up_and_down='use_up_and_down' in specials)
                need_right_left = self.menu_utils.find_menu_icon(
                    need_right_left, second_specials, 'find_2', second_multiple_images,
                    use_r1_and_l1='use_r1_and_l1' in specials, use_up_and_down='use_up_and_down' in specials)
            if main_counter_param_2 == 'in':
                if need_right_left:
                    for i in range(the_path[main_counter][3]):
                        if 'use_r1_and_l1' in specials:
                            # pass
                            new_print(self.fifa_account, 'press a normal r1 step 1')
                            self.ps4_buttons.r1()
                        else:
                            new_print(self.fifa_account, 'press a normal right')
                            self.ps4_buttons.right()
                        time.sleep(1)
                # if not 'use_r1_and_l1' in specials:
                if not 'dont_need_enter' in specials:
                    new_print(self.fifa_account, 'press a normal cross step 1')
                    self.ps4_buttons.cross()
                time.sleep(1)

                # if 'use_r1_and_l1' in specials:
                # todo : fix shit bellow.
                # if 'use_r1_and_l1' in specials:
                #     for num in range(10):
                #         current_state = self.just_find_state()
                #         new_print(self.fifa_account, 'current state : ', current_state, '    ',
                #                   the_path[main_counter], '    ',
                #                   the_path[main_counter][1])
                #         # if current_state == 'ultimate_team':
                #         #     current_state = 'home'
                #         if the_path[main_counter][1] != current_state:
                #             new_print(self.fifa_account, 'press a normal r1 step 2')
                #             self.ps4_buttons.r1()
                #             time.sleep(3)
                #         else:
                #             break
                time.sleep(1)
            elif main_counter_param_2 == 'out':
                new_print(self.fifa_account, 'press a normal circle')
                self.ps4_buttons.circle(press_time=.4)
                time.sleep(1)
            # elif main_counter_param_2 == 'right':
            #     for i in range(the_path[main_counter][3]):
            #         new_print(self.fifa_account,'press a normal right')
            #         self.ps4_buttons.right()
            #         self.ps4_buttons.cross()
            #         time.sleep(.5)
            elif main_counter_param_2 == 'left':
                if need_right_left:
                    for i in range(the_path[main_counter][3]):
                        if 'use_r1_and_l1' in parent_specials:
                            new_print(self.fifa_account, 'press a normal l1')
                            self.ps4_buttons.l1()
                        else:
                            new_print(self.fifa_account, 'press a normal left')
                            self.ps4_buttons.left()
                if not 'use_r1_and_l1' in parent_specials:
                # if True:
                    new_print(self.fifa_account, 'press a normal cross step 2')
                    self.ps4_buttons.cross()
                time.sleep(1)

            elif main_counter_param_2 == 'right':
                if need_right_left:
                    for i in range(the_path[main_counter][3]):
                        if 'use_r1_and_l1' in parent_specials:
                            new_print(self.fifa_account, 'press a normal r1 step 3')
                            self.ps4_buttons.r1()
                        else:
                            new_print(self.fifa_account, 'press a normal right 2')
                            self.ps4_buttons.right()
                if not 'use_r1_and_l1' in parent_specials:
                    new_print(self.fifa_account, 'press a normal cross step 3')
                    self.ps4_buttons.cross()
                time.sleep(1)

            if (main_counter_param_2 == 'out') and ('confirm_exit' in specials):
                time.sleep(1)
                self.ps4_buttons.up()
                time.sleep(1)
                self.ps4_buttons.cross()
                time.sleep(1)

            if special_order == 'dont_check_last_state':
                if the_path[main_counter][1] == second_state:
                    return True

            need_to_press = 0
            if special_order == 'check_key':
                need_to_press = 5
            no_need_to_control = False
            if ('cross_until_connecting' in specials) and (special_order != 'just_enter_fifa'):
                new_print(self.fifa_account, 'cross until connection')
                temp_count = 0
                for num in range(50):
                    temp_count += 1
                    if temp_count % 10 == 0:
                        temp_state = self.just_find_state()
                        if temp_state:
                            first_state = temp_state
                            new_print(self.fifa_account, 'new state =', first_state,
                                      ' second state = ', second_state)
                            the_path = self.menu_utils.map_path(self.all_menus_dict, first_state, second_state)
                            main_counter = 0
                            no_need_to_control = True
                            break
                    if temp_count > 40:
                        break
                    self.get_screen_shot()
                    error_status = self.errors()
                    new_print(self.fifa_account, 'error status : ', error_status)
                    if error_status:
                        break
                    if self.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/need_use_key.png'),
                            'screen_shot_tmp.jpg'
                    ) or self.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/need_use_key_2.png'),
                        'screen_shot_tmp.jpg'
                    ) or self.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/need_use_key_3.png'),
                        'screen_shot_tmp.jpg'
                    ):
                        return False
                    if self.menu_utils.control_state(the_path[main_counter][1]):
                        break
                    if self.has_image(
                            os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/ea_connecting.png'),
                            'screen_shot_tmp.jpg'
                    ):
                        break
                    if temp_count >= need_to_press:
                        new_print(self.fifa_account, 'need to press cross until ea connect')
                        self.ps4_buttons.cross()
                    time.sleep(3)

            if special_order == 'check_for_ban':
                self.get_screen_shot()
                if self.has_image(
                        os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/console_transfer_ban.png'),
                        'screen_shot_tmp.jpg'):
                    new_print(self.fifa_account, 'console transfer ban sign ...')
                    self.ps4_buttons.cross()
                    return False

            if (no_need_to_control) or ('no_need_check_second_state' in second_specials):
                continue

            wait_time = 5
            for special in specials:
                if special.find('need_sleep') != -1:
                    wait_time = 20
            main_counter += 1
            if os.path.exists(os.path.join(
                    BASE_DIR, f'utils/{self.fifa_account.platform}_controls/{second_item.name}.png')
            ) and special_order != 'just_enter_fifa':
                new_print(self.fifa_account, 'need to control second state, wait time = ', wait_time)
                # new_print(self.fifa_account, 'wait time = ', wait_time)
                waiting_images = [
                    os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/{second_item.name}.png')
                ]
                for image_item in second_multiple_images:
                    waiting_images.append(
                        os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/{image_item}.png')
                    )
                if not self.wait_for_images(waiting_images, wait_time=wait_time, special='find_state'):
                    new_print(self.fifa_account, 'I missed my way')
                    if special_order == 'check_for_ban':
                        self.get_screen_shot()
                        if self.has_image(os.path.join(
                                BASE_DIR,
                                f'utils/{self.fifa_account.platform}_controls/console_transfer_ban.png'),
                                'screen_shot_tmp.jpg'):
                            self.ps4_buttons.cross()
                            return False
                    first_state = self.menu_utils.find_state()
                    new_print(self.fifa_account, 'new state =', first_state)
                    the_path = self.menu_utils.map_path(self.all_menus_dict, first_state, second_state)
                    main_counter = 0

        return True

    # def console_update_credit(self):
    #     self.get_screen_shot()
    #     self.__get_credit_part()

    # def __get_credit_part(self):
    #     credit = self.get_image_position(
    #         os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/credit_sign.png'),
    #         'screen_shot_tmp.jpg')
    #     top_left = credit.get('top_right')
    #     credit_width = credit.get('width')
    #     credit_height = credit.get('height')
    #     img = cv2.imread("screen_shot_tmp.jpg")
    #     crop_credit = img[top_left[1]:top_left[1] + credit_height,
    #                   top_left[0]:top_left[0] + (credit_width * 3)]
    #     crop_credit = cv2.cvtColor(crop_credit, cv2.COLOR_BGR2GRAY)
    #     cv2.imwrite('credit_tmp.jpg', crop_credit)



    def list_on_transfer_market(self, start_price, buy_now_price, list_with_default_values=False, second=False,
                                player_min_price=0, player_max_price=0, wait_for_list=False):
        return self.transfer_list_utils.list_on_transfer_market(
            start_price, buy_now_price, list_with_default_values=list_with_default_values, second=second,
            player_min_price=player_min_price, player_max_price=player_max_price, wait_for_list=wait_for_list)

    def quick_sell_from_stadium_club(self):
        self.ps4_buttons.square()
        time.sleep(1)
        self.ps4_buttons.press_left_joystick(100, 250)
        time.sleep(.3)
        self.ps4_buttons.press_cross()
        time.sleep(3)
        self.ps4_buttons.release_cross()
        self.ps4_buttons.release_left_joystick()
        time.sleep(.3)

    def get_screen_text(self, screen_name='', config='', convert=False, convert_type=1):
        return self.screen_utils.get_screen_text(screen_name=screen_name, config=config, convert=convert, convert_type=convert_type)

    def search_player(self, player_name, player_rate, player_asset_id, max_buy_now=0, special='', reset_data=1,
                      search_start_price=0, search_buy_now_price=0,
                      filter_target: SBCTargetFilter = None,
                      use_target_and_filter=False, wait_for_fix_name=True, player_special_name=None,
                      search_start_min_price=0):
        if filter_target:
            buy_data = f'{filter_target.id} -- {filter_target.position} -- {filter_target.level} -- {filter_target.rarity_ids}'
        else:
            buy_data = f'{player_name} -- {player_rate} -- {player_asset_id}'
        new_print(self.fifa_account, 'search player in console : ', buy_data, ' -- ', max_buy_now,
                  ' -- ', special, ' -- ', reset_data, ' -- ', search_start_price, ' -- ', search_buy_now_price,
                  ' -- sp name ', player_special_name)
        # todo :  ea bug. every search need reset data. remove this after fix.
        reset_data = 1
        self.go_to_state('transfer_market', 'search_players')
        if self.has_image(os.path.join(
            BASE_DIR,
            f'utils/{self.fifa_account.platform}_controls/player_search_not_found.png'),
            'screen_shot_tmp.jpg'
        ) or self.has_image(os.path.join(
            BASE_DIR,
            f'utils/{self.fifa_account.platform}_controls/player_search_not_found_start.png'),
            'screen_shot_tmp.jpg'
        ):
            new_print(self.fifa_account, 'already in player search . press circle')
            self.ps4_buttons.circle()
            time.sleep(1)
        if reset_data:
            new_print(self.fifa_account, 'need to reset data')
            self.ps4_buttons.r3()
            time.sleep(.5)
            if filter_target:
                new_print(self.fifa_account, 'search player find filter : ', vars(filter_target))
                # todo : in new development
                # self.search_player_set_filters(
                #     level=filter_target.level, rarity_ids=filter_target.rarity_ids, position=filter_target.position,
                #     nation=filter_target.nation, team=filter_target.team, league=filter_target.league)
                #
                if filter_target.level or filter_target.rarity_ids:
                    quality_name = f'{filter_target.level or "bronze"}{filter_target.rarity_ids or 0}'
                    new_print(self.fifa_account, 'search player find quality 2 ', quality_name)
                    if self.move_to_next_icon('quality') != 'success':
                        new_print(self.fifa_account, 'not hovered quality 2')
                        return self.search_player(
                            player_name=player_name, player_rate=player_rate, player_asset_id=player_asset_id,
                            max_buy_now=max_buy_now, special=special, reset_data=reset_data,
                            search_start_price=search_start_price, search_buy_now_price=search_buy_now_price,
                            filter_target=filter_target, use_target_and_filter=use_target_and_filter)
                    self.ps4_buttons.cross()
                    time.sleep(1)
                    self.transfer_list_utils.find_quality(quality_name)
                    time.sleep(2)
                    if not self.transfer_list_utils.check_selected_quality(quality_name):
                        new_print(self.fifa_account, 'selected quality not fixed')
                        return self.search_player(
                            player_name=player_name, player_rate=player_rate, player_asset_id=player_asset_id,
                            max_buy_now=max_buy_now, special=special, reset_data=reset_data,
                            search_start_price=search_start_price, search_buy_now_price=search_buy_now_price,
                            filter_target=filter_target, use_target_and_filter=use_target_and_filter)
                if filter_target.position:
                    new_print(self.fifa_account, 'search player find position', filter_target.position)
                    if self.move_to_next_icon('position') != 'success':
                        new_print(self.fifa_account, 'not hovered position')
                        return self.search_player(
                            player_name=player_name, player_rate=player_rate, player_asset_id=player_asset_id,
                            max_buy_now=max_buy_now, special=special, reset_data=reset_data,
                            search_start_price=search_start_price, search_buy_now_price=search_buy_now_price,
                            filter_target=filter_target, use_target_and_filter=use_target_and_filter)
                    self.ps4_buttons.cross()
                    time.sleep(1)
                    self.transfer_list_utils.find_position(filter_target.position)
                    time.sleep(1)
                if filter_target.nation:
                    nation_moves = SBCTargetFilterNationMoves.objects.filter(nation=filter_target.nation).first()
                    if not nation_moves:
                        new_print(self.fifa_account, 'nation not found')
                        set_sbc_status(self.sbc_worker, 'nation not found')
                        time.sleep(100)
                        return False
                    new_print(self.fifa_account, 'search player find nation', filter_target.nation)
                    if self.move_to_next_icon('nation') != 'success':
                        new_print(self.fifa_account, 'not hovered nation')
                        return self.search_player(
                            player_name=player_name, player_rate=player_rate, player_asset_id=player_asset_id,
                            max_buy_now=max_buy_now, special=special, reset_data=reset_data,
                            search_start_price=search_start_price, search_buy_now_price=search_buy_now_price,
                            filter_target=filter_target, use_target_and_filter=use_target_and_filter)
                    self.ps4_buttons.cross()
                    time.sleep(1)
                    self.transfer_list_utils.find_nation(nation_moves)
                    time.sleep(2)

                if filter_target.team:
                    new_print(self.fifa_account, 'search player find club', filter_target.team)
                    team_moves = SBCTargetFilterClubMoves.objects.filter(team=filter_target.team).first()
                    if not team_moves:
                        new_print(self.fifa_account, 'club not found')
                        set_sbc_status(self.sbc_worker, 'club not found')
                        time.sleep(100)
                        return False
                    league_moves = SBCTargetFilterLeagueMoves.objects.filter(league=filter_target.league).first()
                    if not league_moves:
                        new_print(self.fifa_account, 'league not found')
                        set_sbc_status(self.sbc_worker, 'league not found')
                        time.sleep(100)
                        return False
                    if self.move_to_next_icon('league') != 'success':
                        new_print(self.fifa_account, 'not hovered league')
                        return self.search_player(
                            player_name=player_name, player_rate=player_rate, player_asset_id=player_asset_id,
                            max_buy_now=max_buy_now, special=special, reset_data=reset_data,
                            search_start_price=search_start_price, search_buy_now_price=search_buy_now_price,
                            filter_target=filter_target, use_target_and_filter=use_target_and_filter)
                    self.ps4_buttons.cross()
                    time.sleep(1)
                    self.transfer_list_utils.find_league(league_moves)
                    time.sleep(1)
                    if self.move_to_next_icon('club') != 'success':
                        new_print(self.fifa_account, 'not hovered club')
                        return self.search_player(
                            player_name=player_name, player_rate=player_rate, player_asset_id=player_asset_id,
                            max_buy_now=max_buy_now, special=special, reset_data=reset_data,
                            search_start_price=search_start_price, search_buy_now_price=search_buy_now_price,
                            filter_target=filter_target, use_target_and_filter=use_target_and_filter)
                    self.ps4_buttons.cross()
                    time.sleep(1)
                    self.transfer_list_utils.find_club(team_moves)
                    time.sleep(2)
                elif filter_target.league:
                    new_print(self.fifa_account, 'search player find league', filter_target.league)
                    league_moves = SBCTargetFilterLeagueMoves.objects.filter(league=filter_target.league).first()
                    if not league_moves:
                        new_print(self.fifa_account, 'league not found')
                        set_sbc_status(self.sbc_worker, 'league not found')
                        time.sleep(100)
                        return False
                    if self.move_to_next_icon('league') != 'success':
                        new_print(self.fifa_account, 'not hovered league')
                        return self.search_player(
                            player_name=player_name, player_rate=player_rate, player_asset_id=player_asset_id,
                            max_buy_now=max_buy_now, special=special, reset_data=reset_data,
                            search_start_price=search_start_price, search_buy_now_price=search_buy_now_price,
                            filter_target=filter_target, use_target_and_filter=use_target_and_filter)
                    self.ps4_buttons.cross()
                    time.sleep(1)
                    self.transfer_list_utils.find_league(league_moves)
                    time.sleep(2)
            if not filter_target or use_target_and_filter:
                # todo : in new development
                if filter_target:
                    new_print(self.fifa_account, 'filter target exists. so move to name.')
                    if self.move_to_next_icon('name') != 'success':
                        new_print(self.fifa_account, 'not hovered name')
                        return self.search_player(
                            player_name=player_name, player_rate=player_rate, player_asset_id=player_asset_id,
                            max_buy_now=max_buy_now, special=special, reset_data=reset_data,
                            search_start_price=search_start_price, search_buy_now_price=search_buy_now_price,
                            filter_target=filter_target, use_target_and_filter=use_target_and_filter)
                counter = 0
                while True:
                    new_print(self.fifa_account, 'search player find player ', player_name, ' rate : ', player_rate)
                    self.ps4_buttons.cross()
                    time.sleep(1)
                    if counter > 2:
                        card_info = get_player_data_by_asset_id(player_asset_id=player_asset_id)
                        if card_info[4]:
                            player_rate = card_info[4]
                        new_print(self.fifa_account, f'can not find player {counter} time so change player rate to {player_rate}')
                        if counter > 20:
                            new_print(self.fifa_account, 'too many try for buy target , break ,'
                                                         ' try counter : ', counter)
                            return 'player name not found'
                    find_player_result = self.transfer_list_utils.find_player(
                        player_name, player_rate, player_asset_id, counter=counter,
                        wait_for_fix_name=wait_for_fix_name, player_special_name=player_special_name)
                    if find_player_result is True:
                        break
                    elif find_player_result == 'player name not found':
                        telegram_send_photo(
                            self.fifa_account,
                            os.path.join(BASE_DIR, 'screen_shot_tmp.jpg'),
                            caption=f'account {self.fifa_account} find player ,'
                                    f' player name : {player_name} {player_rate}',
                            message_thread_id=ARZBAZI_REPORT_TOPIC_PLAYERS_NOT_FOUND_THREAD_MESSAGE_ID)
                        self.ps4_buttons.circle()
                        return 'player name not found'
                    counter += 1
                    # self.ps4_buttons.circle()
                    # time.sleep(0.5)
                    self.ps4_buttons.circle()
                    time.sleep(2)
                    # new_print(self.fifa_account,'search failed')
                    # self.ps4_buttons.circle()
                    # time.sleep(0.5)
                    # self.ps4_buttons.circle()
                    # time.sleep(1)
                    # return False
        # self.ps4_buttons.down(sleep_after=0.5)
        self.move_to_next_icon('pricing')
        time.sleep(.5)

        self.ps4_buttons.square()
        time.sleep(0.5)
        self.ps4_buttons.cross()
        time.sleep(1)
        if search_start_price:
            time.sleep(1)
            search_res = self.search_player_price(
                price=get_previous_price_grade(search_start_price),
                price_type='min_start', default_price=150)
            if search_res == 'can not find price':
                self.ps4_buttons.circle()
                time.sleep(1)
                self.ps4_buttons.circle()
                time.sleep(1)
                return False
            time.sleep(0.5)
            search_res = self.search_player_price(
                price=search_start_price, price_type='max_start', default_price=search_start_price)
            if search_res == 'can not find price':
                self.ps4_buttons.circle()
                time.sleep(1)
                self.ps4_buttons.circle()
                time.sleep(1)
                return False
            time.sleep(0.5)
        if search_start_min_price:
            time.sleep(1)
            search_res = self.search_player_price(
                price=search_start_min_price,
                price_type='min_start', default_price=150)
            if search_res == 'can not find price':
                self.ps4_buttons.circle()
                time.sleep(1)
                self.ps4_buttons.circle()
                time.sleep(1)
                return False
            time.sleep(0.5)
        if search_buy_now_price:
            if search_start_price:
                search_res = self.search_player_price(
                    price=get_previous_price_grade(search_buy_now_price),
                    price_type='min_buy', default_price=get_previous_price_grade(search_start_price))
                if search_res == 'can not find price':
                    self.ps4_buttons.circle()
                    time.sleep(1)
                    self.ps4_buttons.circle()
                    time.sleep(1)
                    return False
            else:
                search_res = self.search_player_price(
                    price=get_previous_price_grade(search_buy_now_price),
                    price_type='min_buy', default_price=150)
                if search_res == 'can not find price':
                    self.ps4_buttons.circle()
                    time.sleep(1)
                    self.ps4_buttons.circle()
                    time.sleep(1)
                    return False
            time.sleep(0.5)
            search_res = self.search_player_price(
                price=search_buy_now_price, price_type='max_buy', default_price=search_buy_now_price)
            if search_res == 'can not find price':
                self.ps4_buttons.circle()
                time.sleep(1)
                self.ps4_buttons.circle()
                time.sleep(1)
                return False
            time.sleep(0.5)

        if max_buy_now and not search_buy_now_price:
            # for i in range(10):
            #     new_print(self.fifa_account,'try to press cross')
            #
            #     self.get_screen_text()
            #     if self.has_image(os.path.join(BASE_DIR, 'utils/controls/set_price_directions.png'),'screen_shot_tmp.jpg'):
            #         break
            default_price = 150
            if search_start_min_price:
                default_price = get_next_price_grade(search_start_min_price)
            search_res = self.search_player_price(price=max_buy_now, price_type='max_buy', default_price=default_price)
            if search_res == 'can not find price':
                self.ps4_buttons.circle()
                time.sleep(1)
                self.ps4_buttons.circle()
                time.sleep(1)
                return False
        self.ps4_buttons.circle()
        time.sleep(0.5)
        self.ps4_buttons.up(sleep_after=1)
        # if reset_data:
        #     self.ps4_buttons.right()
        #     self.ps4_buttons.square()
        #     if special == 'gold_rare':
        #         self.ps4_buttons.cross()
        #         time.sleep(1.2)
        #         # self.search_player_quality(card_name=special)
        #         self.ps4_buttons.down()
        #         self.ps4_buttons.down()
        #         self.ps4_buttons.cross()
        #     self.ps4_buttons.left()
        self.get_screen_shot()
        if not self.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/search_players.png'),
                'screen_shot_tmp.jpg'):
            return False
        self.ps4_buttons.triangle()
        FifaAccountSearch.objects.create(fifa_account=self.fifa_account, search_time=timezone.localtime())
        new_print(self.fifa_account, 'len search_number = ',
                  FifaAccountSearch.objects.filter(fifa_account=self.fifa_account).count())
        self.wait_for_image(os.path.join(
            BASE_DIR,
            f'utils/{self.fifa_account.platform}_controls/transfer_market_no_search_result.png'),
            wait_time=15,
            special='live_search_results.png')
        return True

    def console_search_player_and_bid(self, player: PlayerCard, start_price=0, buy_now_price=0, max_change_grade=7,
                                      search_start_price=0, search_buy_now_price=0, expire_time=0,
                                      player_min_price=0, player_max_price=0,
                                      wait_for_list=False, special='',
                                      target_filter: SBCTargetFilter = None, sbc_price=0,
                                      use_target_and_filter=False, wait_for_fix_name=True, buy_timeout_time=None,
                                      owner_count=0, contract_count=0):
        need_error = False
        try:
            new_print(
                self.fifa_account,
                'search and bid in console -- ',
                player, ' -- ', start_price, ' -- ', buy_now_price, ' -- ', max_change_grade,
                search_start_price, ' -- ', search_buy_now_price, ' -*- ', expire_time, ' -*- ', player_min_price,
                player_max_price, ' -- ', wait_for_list, ' -- ', special, ' -+- ', target_filter,
                ' -+- ', sbc_price)
            bought = 0
            bought_price = 0
            first_time = 1
            for i in range(max_change_grade):
                price = player.price
                if sbc_price:
                    price = sbc_price
                if target_filter:
                    try:
                        target_filter.refresh_from_db()
                    except:
                        pass
                    price = target_filter.buy_now_price
                for j in range(i):
                    price = get_next_price_grade(price)
                max_buy_now = price
                # if start_price:
                #     max_buy_now = price
                # else:
                #     max_buy_now = get_next_price_grade(price)
                card_info = get_player_data_by_asset_id(player_asset_id=player.asset_id)
                player_special_name = None
                if card_info[1]:
                    player_special_name = card_info[1]
                search_player_result = self.search_player(
                    player.name, player.rating, player.asset_id,
                    max_buy_now=max_buy_now,
                    reset_data=first_time,
                    search_start_price=search_start_price,
                    search_buy_now_price=search_buy_now_price,
                    special=special,
                    filter_target=target_filter,
                    use_target_and_filter=use_target_and_filter,
                    wait_for_fix_name=wait_for_fix_name,
                    player_special_name=player_special_name if sbc_price else None,
                )
                if not search_player_result:
                    new_print(self.fifa_account, 'search player result : sid')
                    return {'result': 'sid'}
                elif search_player_result == 'player name not found':
                    new_print(self.fifa_account, 'search player result : player name not found, press three circle')

                    self.ps4_buttons.circle()
                    time.sleep(1)
                    self.ps4_buttons.circle()
                    time.sleep(1)
                    self.ps4_buttons.circle()
                    time.sleep(4)
                    return {'result': 'player name not found'}
                first_time = 0
                buy_try = 3
                if expire_time:
                    # expire_time = different_by_seconds
                    buy_try = 50
                if self.has_search_result():
                    for num2 in range(buy_try):
                        can_buy = True
                        if expire_time:
                            # different_by_seconds = (timezone.localtime() - expire_time).total_seconds()
                            # different_by_seconds = 3600 - different_by_seconds
                            system_time = get_db_time(timezone_=TIME_ZONE)
                            aware_system_time = timezone.make_aware(system_time)
                            different_by_seconds = (expire_time - aware_system_time).total_seconds()
                            new_print(self.fifa_account, 'different_by_seconds 4 = ', different_by_seconds,
                                      ' expire_time : ', expire_time, ' system time 2 : ', system_time ,
                                      ' aware systme time : ', aware_system_time)
                            remaining_time = different_by_seconds
                            for j in range(2):
                                try:
                                    remaining_time = self.transfer_list_utils.get_remaining_time()
                                    break
                                except:
                                    time.sleep(1.5)
                            new_print(self.fifa_account, 'remaining time =', remaining_time, ' counter ', num2)
                            if remaining_time > different_by_seconds + 5:
                                break
                            if remaining_time < different_by_seconds - 25:
                                can_buy = False
                            if remaining_time is False and num2 == 10 and owner_count:
                                new_print(self.fifa_account, 'cant read remaining , press circle')
                                self.ps4_buttons.circle()
                                telegram_send_photo(self.fifa_account, os.path.join(BASE_DIR, 'screen_shot_tmp.jpg'),
                                                    caption=f'account {self.fifa_account} error on discharge , get remaingin time',
                                                    message_thread_id=ARZBAZI_REPORT_TOPIC_DISCHARGE_ERROR_THREAD_MESSAGE_ID)

                        elif num2 > 0:
                            next_page_press = int(random.randint(1, 6))
                            for nm in range(next_page_press):
                                self.ps4_buttons.r1()
                                time.sleep(.5)
                        if can_buy:
                            if owner_count:
                                check_owner_contract_result = self.transfer_list_utils.check_owner_contract(
                                    owner_count=owner_count, contract_count=contract_count
                                )
                                if check_owner_contract_result.get('status') == 'failed':
                                    new_print(self.fifa_account, 'check owner and contract failed : ',
                                              check_owner_contract_result)
                                    self.get_screen_shot()
                                    if self.has_image(os.path.join(
                                            BASE_DIR,
                                            f'utils/{self.fifa_account.platform}_transfer_list_icons/player_data_icon.png'),
                                            'screen_shot_tmp.jpg'):
                                        self.ps4_buttons.circle()
                                    time.sleep(2)
                                    if num2 < 2:
                                        continue
                                    return {'result': 'not_bought'}
                            if buy_timeout_time and timezone.localtime() > buy_timeout_time:
                                new_print(self.fifa_account, 'buy time expire : ',
                                          timezone.localtime(), ' < ', buy_timeout_time)
                                self.ps4_buttons.circle()
                                return {'result': 'not_bought'}
                            if self.transfer_list_utils.buy_now(
                                    # start_price=start_price, buy_now_price=buy_now_price,
                                    # player_min_price=player_min_price,
                                    # player_max_price=player_max_price,
                                    wait_for_list=wait_for_list):
                                bought = 1
                                bought_price = max_buy_now
                                break
                            else:
                                self.get_screen_shot()
                                if self.has_image(os.path.join(
                                        BASE_DIR,
                                        f'utils/{self.fifa_account.platform}_controls/check_for_inside_bidding.png'),
                                        'screen_shot_tmp.jpg'):
                                    # self.ps4_buttons.cross()
                                    # time.sleep(0.5)
                                    self.cant_buy_item_counter += 1
                                    if self.cant_buy_item_counter > 3:
                                        self.cant_buy_item_counter = 0
                                        new_print(
                                            self.fifa_account,
                                            'item will added to transfer target its a bad move . will ask from web app',
                                            'cant buy counter : ', self.cant_buy_item_counter)
                                        for num in range(2):
                                            self.ps4_buttons.circle()
                                            time.sleep(0.5)
                                        self.console_close_ultimate(need_get_new_sid=False)
                                        need_error = True
                                        new_print(
                                            self.fifa_account,
                                            'need to recheck credit from web')
                                        return {'result': 'need_check_credit'}
                                        # raise Exception('need to recheck credit from web')
                                    else:
                                        new_print(self.fifa_account,
                                                  'cant buy item but dont need check credit , ',
                                                  self.cant_buy_item_counter)
                                        self.ps4_buttons.circle()
                                        time.sleep(1)

                        self.ps4_buttons.right()
                        time.sleep(0.2)
                    if not bought:
                        self.ps4_buttons.circle()
                        time.sleep(1)
                else:
                    new_print(self.fifa_account, 'search player has no result , press circle')
                    self.ps4_buttons.cross()
                    time.sleep(1)
                if bought:
                    self.fifa_account.refresh_from_db()
                    if self.fifa_account.credit - price < 0:
                        new_print(self.fifa_account, 'credit can not lower than 0 . set it to 1000. credit : ',
                                  self.fifa_account.credit, ' price : ', price)
                        self.fifa_account.credit = 1000
                    else:
                        self.fifa_account.credit -= price
                    self.fifa_account.save(update_fields=['credit'])
                    break

            # if not bought:
            #     self.search_player(player.name, player.rating,
            #                                     max_buy_now=get_next_price_grade(get_next_price_grade(player.price)),
            #                                     special=player.special_name,
            #                                     reset_data=1)
            #     if self.has_search_result():
            #         for i in range(3):
            #             if self.buy_now():
            #                 bought = 1
            #                 break
            #             else:
            #                 self.ps4_buttons.right()
            #                 time.sleep(0.2)
            if not wait_for_list:
                new_print(self.fifa_account, 'not waiting for list')
                if (not self.wait_for_images(
                        [os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/live_search_results.png'),
                         os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/time_remaining.png'),
                         os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/search_players.png'),
                         os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/transfer_market_active.png'),
                         ],
                        wait_time=3) and bought):
                    new_print(self.fifa_account, 'live_search_results not found')
                    self.ps4_buttons.cross()
                    time.sleep(1)
                    self.ps4_buttons.r2()
                    time.sleep(2)
                if self.just_find_state() not in ['search_players', 'transfers']:
                    new_print(self.fifa_account, 'not in search player , press circle')
                    self.ps4_buttons.circle()
                time.sleep(1)
            if bought:
                new_print(self.fifa_account, 'item bought')
                return {'result': True, 'bought_price': bought_price}
            else:
                new_print(self.fifa_account, 'could not bought item')
                return {'result': 'not_bought'}
        except Exception as error_str:
            new_print(self.fifa_account, 'error 70 : ', traceback.format_exc())
            self.console_close_ultimate(need_get_new_sid=False, state='home_main')
            if need_error:
                if self.fifa_account.use_request_login:
                    new_print(self.fifa_account, 'try to update credit')
                    try:
                        login_result = logout_login(self.sbc_solver_instance, self.sbc_worker, self.fifa_account)
                        if login_result.get('status_bool') is False:
                            new_print(self.fifa_account, 'login failed , ', login_result)
                            return {'result': 'sid'}
                        self.sbc_solver_instance.update_credit()
                    except:
                        new_print(self.fifa_account, 'can not update credit : ', traceback.format_exc())
                raise Exception('need to recheck credit from web')
            if error_str.__str__() == 'cant set price for this one error':
                raise Exception('need sell from web app')
            return {'result': 'sid'}

    def move_to_next_icon(self, next_icon_name, try_counter=0):
        return self.transfer_list_utils.move_to_next_icon(next_icon_name, try_counter=try_counter)

    def get_image_position(self, small_image_name, large_image_name):
        return get_image_position(small_image_name, large_image_name)

    def search_player_price(self, price: int = 0, price_type='max_buy', default_price=0):
        # todo : search min_bid and max_bid
        new_print(self.fifa_account, 'search_player_price : ', price, ' -- ', price_type,
                  ' default_price ', default_price)
        for nm in range(20):
            self.get_screen_shot()
            if self.has_image(
                    os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_search_player_icons/{price_type}.png'),
                    "screen_shot_tmp.jpg"
            ):
                break
            self.ps4_buttons.down(sleep_after=.5)
            if nm > 15:
                new_print(self.fifa_account, '** can not find price **')
                return 'can not find price'
        if price:
            if default_price:
                self.ps4_buttons.right()
                self.transfer_list_utils.set_price_with_l_and_r(default_price, price)
            else:
                self.ps4_buttons.cross()
                self.transfer_list_utils.search_player_select_price(price)

    # def search_player_quality(self, card_name: str):
    #     direction_right = True
    #     current_pos = 0
    #     for i in range(100):
    #         time.sleep(.3)
    #         self.get_screen_shot()
    #         if self.has_image(os.path.join(BASE_DIR, 'utils/quality/{}_active.PNG'.format(card_name)),
    #                           'screen_shot_tmp.jpg'):
    #             self.ps4_buttons.cross()
    #             break
    #         if current_pos == 2:
    #             current_pos = 0
    #             direction_right = not direction_right
    #             self.ps4_buttons.down()
    #         elif direction_right:
    #             self.ps4_buttons.right()
    #             current_pos += 1
    #         else:
    #             self.ps4_buttons.left()
    #             current_pos += 1

    def has_search_result(self):
        self.get_screen_shot()
        if self.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/transfer_market_no_search_result.png'),
                'screen_shot_tmp.jpg'):
            return False
        return True

    def read_coin(self):
        raise Exception('don`t read coin')
        self.get_screen_shot()
        coin_pos = self.get_image_position(os.path.join(
            BASE_DIR,
            f'utils/{self.fifa_account.platform}_controls/coin_sign.png'),
            'screen_shot_tmp.jpg')
        top_left = coin_pos.get('top_right')
        point_pos = self.get_image_position(os.path.join(
            BASE_DIR,
            f'utils/{self.fifa_account.platform}_controls/point_sign.png'),
            'screen_shot_tmp.jpg')
        bottom_right = point_pos.get('bottom_left')
        print(top_left)
        print(bottom_right)
        img = cv2.imread("screen_shot_tmp.jpg")
        crop_player_name = img[top_left[1]:bottom_right[1],
                           top_left[0]:bottom_right[0]]
        crop_player_name = cv2.cvtColor(crop_player_name, cv2.COLOR_BGR2GRAY)
        cv2.imwrite('coin_tmp.jpg', crop_player_name)
        coin = self.get_screen_text('coin_tmp.jpg',
                                    config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789',
                                    convert=True)
        return int(coin)



    def buy_contract(self, need_contracts, manager=False):
        return self.transfer_list_utils.buy_contract(need_contracts=need_contracts, manager=manager)

    def buy_healing(self, need_heals):
        return self.transfer_list_utils.buy_healing(need_heals=need_heals)

    # def buy_position_modifier(self, need_position_modifier, price=2000, try_counter=0):
    #     new_print(self.fifa_account, 'need to buy position modifier, need = ', need_position_modifier)
    #     self.go_to_state('ultimate_team', 'search_consumables')
    #     time.sleep(0.5)
    #     self.ps4_buttons.r3()
    #     time.sleep(0.5)
    #     self.ps4_buttons.cross()
    #     time.sleep(0.5)
    #     self.ps4_buttons.right(sleep_after=0.5)
    #     self.ps4_buttons.right(sleep_after=0.5)
    #     self.ps4_buttons.cross()
    #     time.sleep(0.5)
    #     self.ps4_buttons.down(sleep_after=0.5)
    #     self.ps4_buttons.cross()
    #     time.sleep(0.5)
    #     # todo : fix bellow price
    #     search_res = self.search_player_price(price=price, default_price=150)
    #     if search_res == 'can not find price':
    #         self.ps4_buttons.circle()
    #         time.sleep(1)
    #         self.ps4_buttons.circle()
    #         time.sleep(1)
    #         if try_counter < 5:
    #             return self.buy_position_modifier(need_position_modifier, try_counter=try_counter + 1)
    #         else:
    #             return self.buy_position_modifier(need_position_modifier - 1)
    #     time.sleep(0.5)
    #     self.ps4_buttons.circle()
    #     time.sleep(0.5)
    #     self.ps4_buttons.up(sleep_after=0.5)
    #     for i in range(need_position_modifier):
    #         bought = False
    #         for j in range(3):
    #             time.sleep(2)
    #             self.ps4_buttons.triangle()
    #             wait_result = self.wait_for_image(os.path.join(
    #                 BASE_DIR,
    #                 f'utils/{self.fifa_account.platform}_controls/transfer_market_no_search_result.png'),
    #                 special='live_search_results.png', wait_time=10)
    #             if wait_result is False:
    #                 if try_counter < 5:
    #                     return self.buy_position_modifier(
    #                         need_position_modifier=need_position_modifier,
    #                         price=price, try_counter=try_counter + 1)
    #                 else:
    #                     return self.buy_position_modifier(
    #                         need_position_modifier=need_position_modifier - 1,
    #                         price=price)
    #             for nm in range(7):
    #                 self.ps4_buttons.r1()
    #                 time.sleep(.5)
    #             for k in range(3):
    #                 if self.buy_now():
    #                     # self.ps4_buttons.circle()
    #                     bought = True
    #                     self.fifa_account.refresh_from_db()
    #                     self.fifa_account.credit -= price
    #                     self.fifa_account.save()
    #                     break
    #                 self.ps4_buttons.right()
    #             self.ps4_buttons.circle()
    #             time.sleep(0.5)
    #             # todo : ea bug. every search need reset data. remove this after fix.
    #             break
    #             # if bought:
    #             #     break
    #         if bought:
    #             return self.buy_position_modifier(need_position_modifier=need_position_modifier - 1)
    #         elif try_counter < 5:
    #             return self.buy_position_modifier(need_position_modifier=need_position_modifier,
    #                                               price=get_next_price_grade(price), try_counter=try_counter + 1)
    #         else:
    #             return self.buy_position_modifier(need_position_modifier=need_position_modifier - 1)



    # def find_remaining_delete(self):
    #     self.get_screen_shot()
    #     img = Image.open('screen_shot_tmp.jpg')
    #     text = pytesseract.image_to_string(img)
    #     tag = 'Club creations remaining: '
    #     club_creation = text.find(tag)
    #     club_remaining = text[(club_creation + len(tag)):(club_creation + len(tag) + 2)]
    #     new_print(self.fifa_account, 'club_remaining : ', club_remaining)
    #     return club_remaining

    # def enter_delete_club_code(self, code: str):
    #     time.sleep(.5)
    #     self.ps4_buttons.up()
    #     self.ps4_buttons.up()
    #     current_number = 3
    #     for num in code:
    #         int_num = int(num)
    #         if int_num == 0:
    #             int_num = 10
    #         result_num = int_num - current_number
    #         if result_num > 0:
    #             for i in range(result_num):
    #                 self.ps4_buttons.right()
    #                 time.sleep(.5)
    #         elif result_num < 0:
    #             for i in range(abs(result_num)):
    #                 self.ps4_buttons.left()
    #                 time.sleep(.5)
    #         self.ps4_buttons.cross()
    #         current_number = int_num
    #     time.sleep(.5)
    #     self.ps4_buttons.option()

    # def find_delete_code(self):
    #     self.get_screen_shot()
    #     img = Image.open('screen_shot_tmp.jpg')
    #     text = pytesseract.image_to_string(img)
    #     code_below = text.find('code below')
    #     delete_code = text[code_below + 11:code_below + 18].strip()
    #     new_print(self.fifa_account, 'delete code = ', delete_code)
    #     return delete_code

    # def select_golden(self, gold_type='kit'):
    #     self.go_to_first_item()
    #     golden_kits_images = os.listdir(os.path.join(BASE_DIR, 'utils/%s' % gold_type))
    #     for i in range(9):
    #         self.get_screen_shot()
    #         for golden_kit_name in golden_kits_images:
    #             if self.has_image(os.path.join(BASE_DIR, 'utils/%s/%s' % (gold_type, golden_kit_name)),
    #                               'screen_shot_tmp.jpg'):
    #                 new_print(self.fifa_account, 'find golden')
    #                 self.ps4_buttons.cross()
    #                 return True
    #         if i in [0, 1, 6, 7]:
    #             self.ps4_buttons.right()
    #         elif i in [2, 5]:
    #             self.ps4_buttons.down()
    #         else:
    #             self.ps4_buttons.left()
    #     new_print(self.fifa_account, 'can not find golden')
    #     print('cant find golden')
    #     input('plz enter after getting screenshot and selecting the golden ones')
    #     return False

    # def go_to_first_item(self):
    #     time.sleep(2)
    #     self.ps4_buttons.left()
    #     time.sleep(.3)
    #     self.ps4_buttons.left()
    #     time.sleep(.3)
    #     self.ps4_buttons.up()
    #     time.sleep(.3)
    #     self.ps4_buttons.up()
    #     time.sleep(.3)

    def create_club(self, need_to_change_state=True):

        new_print(self.fifa_account, 'need to create club')
        # faze 2
        # if need_to_change_state:
        #     self.go_to_state('play_main', 'home_main')
        #     self.go_to_state('home_main', 'ultimate_team', special_order='dont_check_last_state')
        # self.wait_for_image(os.path.join(
        #     BASE_DIR,
        #     f'utils/{self.fifa_account.platform}_controls/delete_club_lets_get_started.png'))
        self.get_screen_shot()
        for i in range(100):
            if not self.has_image(
                os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/delete_club_advance.png'),
                'screen_shot_tmp.jpg'):
                new_print(self.fifa_account, 'advance not found. press a cross')
                self.ps4_buttons.cross()
                time.sleep(1)
                self.get_screen_shot()
        if not self.has_image(
                os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/delete_club_advance.png'),
                'screen_shot_tmp.jpg'):
            new_print(self.fifa_account, 'cannot find delete club advance')
            return False
        for ii in range(10):
            self.get_screen_shot()
            if self.has_image(
                os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/delete_club_advance.png'),
                'screen_shot_tmp.jpg'):
                new_print(self.fifa_account, 'delete club advance found')
                time.sleep(10)
                self.ps4_buttons.option()
                time.sleep(5)
                self.ps4_buttons.cross()
                time.sleep(5)
                self.ps4_buttons.cross()
                time.sleep(5)
                self.ps4_buttons.up()
                time.sleep(5)
                self.ps4_buttons.cross()
                time.sleep(10)
                self.ps4_buttons.cross()
                time.sleep(4)
                self.ps4_buttons.cross()
                time.sleep(4)
        # self.select_golden()
        self.ps4_buttons.cross()
        time.sleep(3)
        # self.select_golden()
        self.ps4_buttons.cross()
        time.sleep(3)
        # self.select_golden()
        self.ps4_buttons.cross()
        time.sleep(5)
        self.ps4_buttons.cross()
        for i in range(100):
            new_print(self.fifa_account, f'press cross until final {i}')
            self.get_screen_shot()
            # todo : image is for xboxs . add xbox360 and ps image
            if has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/fut_main_menu_sign.png'),
                    'screen_shot_tmp.jpg'
            ):
                self.ps4_buttons.circle()
                break
            else:
                self.ps4_buttons.cross()
            time.sleep(2)

        # faze 3
        # self.quick_sell_first_items()
        return True

    def release_buttons_after_game(self):
        self.break_get_minimap_data = True
        self.r2_status = 0
        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()
        self.ps4_buttons.reset_to_default()

    def play_squad_battle_games(self, play_games=40):
        new_print(self.fifa_account, 'need to do play games : ', play_games)
        self.go_to_state('ultimate_team', 'opponent_select')
        # time.sleep(7)
        # while True:
        #     self.get_screen_shot()
        #     if self.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, 'played squad battle games account_played_games = ',
                  self.fifa_account.account_played_games,
                  '\nstart a game in squad battle')

        # new_print(self.fifa_account, 'start a game in squad battle')
        # self.ps4_buttons.cross()
        # time.sleep(5)

        # 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()
        played_games_counter = 0
        while (
                played_games_counter < play_games or
                self.fifa_account.squad_special_game_one is False or
                self.fifa_account.squad_special_game_two is False
        ) and self.fifa_account.run_squad_battle and self.sbc_worker.must_done is False:
            set_main_log(self.sbc_worker, f'playing game : {self.fifa_account.account_played_games}')
            set_sub_log(self.sbc_worker, 'start playing %s' % self.fifa_account.account_played_games)
            new_print(self.fifa_account, f'start playing {self.fifa_account.account_played_games}')
            # todo : in new development
            self.go_to_state('ultimate_team', 'opponent_select')
            #
            set_sbc_status(self.sbc_worker, f'start game {self.fifa_account.account_played_games}')
            # self.do_special_move(self.fifa_account.account_played_games)
            count = 0
            difficulty_set = False
            # todo : uncomment bellow after fix player bot
            difficulty_name = 'amateur'
            # difficulty_name = 'beginner'
            current_opponent_rating = 100
            success = False
            # if self.fifa_account.fifaaccountsquadgame_set.all().count()>105:
            # if self.fifa_account.console.name in [120, 2040, 2041, 2042, 2043, 2044, 2045]:
            if self.fifa_account.special_squad_ready_to_play:
                difficulty_name = 'semi_pro'
            while count < 100:
                count += 1
                self.get_screen_shot()
                check_squad_errors_result = self.play_football_utils.check_squad_errors()
                if check_squad_errors_result == 'continue':
                    continue
                elif check_squad_errors_result:
                    return check_squad_errors_result

                # need_something = False
                # need_text = ''
                # if self.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')
                #         continue
                # elif self.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.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.has_image(os.path.join(
                #         BASE_DIR,
                #         f'utils/{self.fifa_account.platform}_controls/concept_error.png'),
                #         'screen_shot_tmp.jpg'
                # ) or self.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.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.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.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.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.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.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)
                #     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.refresh_from_db()
                #     self.sbc_worker.main_squad = False
                #     self.sbc_worker.save()
                #     new_print(self.fifa_account, 'need to reset 1')
                #     self.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'
                #     # raise Exception('need to reset active squad')
                # if count == 5:
                #     if self.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.get_screen_shot()
                #         if self.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 self.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/reply_squad.png'),
                        'screen_shot_tmp.jpg'):
                    # todo : just xbox360 and ps image added. add other device images too
                    new_print(self.fifa_account, 'reply squad special game message appear. close it.')
                    self.get_screen_shot()
                    if self.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/confirm_reply_squad.png'),
                            'screen_shot_tmp.jpg'):
                        self.ps4_buttons.up(sleep_after=.5)
                    self.ps4_buttons.cross()
                    time.sleep(3)
                    continue
                if self.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/opponent_select.png'),
                        'screen_shot_tmp.jpg'):
                    self.fifa_account.refresh_from_db()

                    # if self.fifa_account.special_squad_ready_to_play:
                    if self.fifa_account.fifaaccountsquadgame_set.all().count() > 100:
                        if (not self.fifa_account.squad_special_game_one or
                                not self.fifa_account.squad_special_game_two):
                            self.play_football_utils.start_opponent(
                                special_game_one=not self.fifa_account.squad_special_game_one,
                                special_game_two=not self.fifa_account.squad_special_game_two,
                            )
                            time.sleep(1)
                            difficulty_name = 'semi_pro'
                        else:
                            difficulty_name, current_opponent_rating = self.play_football_utils.start_opponent_2()
                            if difficulty_name == 'can not find good opponent':
                                new_print(self.fifa_account, 'can not find good opponent , sleep 5 minute')
                                time.sleep(60 * 5)
                                return 'can not find good opponent'
                    else:
                        self.play_football_utils.start_opponent(
                            special_game_one=not self.fifa_account.squad_special_game_one,
                            special_game_two=not self.fifa_account.squad_special_game_two,
                        )
                        time.sleep(1)
                        if self.fifa_account.squad_special_game_one and self.fifa_account.squad_special_game_two:
                            self.get_screen_shot()
                            current_opponent_rating = self.play_football_utils.get_opponent_rating()
                            # if self.fifa_account.special_squad_ready_to_play:
                            #     if current_opponent_rating and 50 < current_opponent_rating <= 70:
                            #         difficulty_name = 'professional'
                            #     elif current_opponent_rating and 70 < current_opponent_rating <= 85:
                            #         difficulty_name = 'semi_pro'
                            if (current_opponent_rating and
                                    50 < current_opponent_rating <= 75 and
                                    self.fifa_account.main_squad_rate > 81):
                                difficulty_name = 'semi_pro'
                    # todo : remove bellow . just for test
                    # if self.fifa_account.console and self.fifa_account.console.name == 136:
                    #     difficulty_name = 'semi_pro'
                    new_print(self.fifa_account, 'opponent selected , rating is : ', current_opponent_rating,
                              'difficulty will be : ', difficulty_name, ' counter : ', count)
                    time.sleep(1)
                    self.ps4_buttons.cross()
                    time.sleep(5)
                    self.get_screen_shot()
                    if self.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/reply_squad.png'),
                            'screen_shot_tmp.jpg'):
                        new_print(self.fifa_account, 'reply squad special game')
                        if not self.has_image(os.path.join(
                                BASE_DIR,
                                f'utils/{self.fifa_account.platform}_controls/confirm_reply_squad.png'),
                                'screen_shot_tmp.jpg'):
                            self.ps4_buttons.up(sleep_after=.5)
                        self.ps4_buttons.cross()
                        time.sleep(3)
                    if count >= 20 and count % 10 == 0 and self.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/your_rank.png'),
                            'screen_shot_tmp.jpg'):
                        new_print(self.fifa_account, 'your rank page seeen? , press circle')
                        self.ps4_buttons.circle()
                        time.sleep(5)
                    continue
                elif not difficulty_set:
                    new_print(self.fifa_account, 'inside difficulty check')
                    self.get_screen_shot()
                    if self.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/squad_battle_go_to_game.png'),
                            'screen_shot_tmp.jpg') or self.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/difficulty_selection.png'),
                        'screen_shot_tmp.jpg') or self.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/difficulty_breakdown.png'),
                        'screen_shot_tmp.jpg'):
                        new_print(self.fifa_account, 'difficulty select founded')
                        time.sleep(1)
                        while True:
                            self.get_screen_shot()
                            if self.has_image(os.path.join(
                                    BASE_DIR,
                                    # f'utils/{self.fifa_account.platform}_controls/beginner_difficulty.png'),
                                    f'utils/{self.fifa_account.platform}_controls/{difficulty_name}_difficulty.png'),
                                    'screen_shot_tmp.jpg'):
                                new_print(self.fifa_account, 'difficulty is set : ', difficulty_name)
                                break
                            else:
                                new_print(self.fifa_account, 'could not see the difficulty')
                                self.ps4_buttons.down()
                                time.sleep(1)
                        difficulty_set = True
                        self.ps4_buttons.cross()
                        self.wait_for_images([
                            os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/squad_in_game.png'),
                            os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/squad_eligible.png'),
                        ])
                        time.sleep(2)
                        continue
                    elif count >= 20 and count % 10 == 0:
                        if self.has_image(os.path.join(
                                    BASE_DIR,
                                    f'utils/{self.fifa_account.platform}_controls/squad_battle_week_end.png'),
                                    'screen_shot_tmp.jpg'):
                            new_print(self.fifa_account, 'squad battle week end')
                            self.ps4_buttons.cross()
                            time.sleep(1)
                        new_print(self.fifa_account,
                                  'difficalty not selected and can`t find defficalty page, press circle')
                        self.ps4_buttons.circle()
                        time.sleep(1)
                        self.ps4_buttons.circle()
                        time.sleep(1)
                        continue
                elif count > 20 and count % 3 == 0 and (self.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/advance_in_go_squad_battle.png'),
                            'screen_shot_tmp.jpg') or self.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/squad_actions_in_go_squad_battle.png'),
                            'screen_shot_tmp.jpg')):
                    new_print(self.fifa_account, 'not going to squad battle? press option')
                    self.ps4_buttons.option()
                    time.sleep(2)
                    continue
                new_print(self.fifa_account, 'press cross , until enter game')
                self.ps4_buttons.cross()
                if self.has_image(
                        os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/scoreboard.png'),
                        'screen_shot_tmp.jpg'
                ):
                    new_print(self.fifa_account, 'find scoreboard')
                    success = True
                    break
                time.sleep(1)
                # count += 1
            if success:
                if not self.fifa_account.squad_special_game_one:
                    set_sub_log(self.sbc_worker, 'game settings setting ...')
                    self.play_football_utils.set_squad_game_settings()
                    # 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
                else:
                    new_print(self.fifa_account, 'no need change settings')
                squad_game = FifaAccountSquadGame.objects.create(
                    fifa_account=self.fifa_account,
                    game_number=self.fifa_account.account_played_games + 1,
                    difficulty=difficulty_name,
                    enemy_team_rate=current_opponent_rating,
                )
                played_games_counter += 1
                self.fifa_account.refresh_from_db()
                if self.fifa_account.squad_special_game_one is False:
                    new_print(self.fifa_account, 'squad_special_game_one game start')
                    set_sub_log(self.sbc_worker, f'before special game one')
                    self.fifa_account.squad_special_game_one = True
                    self.fifa_account.save(update_fields=['squad_special_game_one'])
                elif self.fifa_account.squad_special_game_two is False:
                    new_print(self.fifa_account, 'squad_special_game_two game start')
                    set_sub_log(self.sbc_worker, f'before special game two')
                    self.fifa_account.squad_special_game_two = True
                    self.fifa_account.save(update_fields=['squad_special_game_two'])
                else:
                    new_print(self.fifa_account, 'one of none special game start',
                              self.fifa_account.account_played_games)
                    set_sub_log(self.sbc_worker, f'before game {self.fifa_account.account_played_games}')
                    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)
                play_game_result = self.play_one_game()
                self.ps4_buttons.reset_to_default()
                close_old_connections()
                if isinstance(play_game_result, dict) and play_game_result.get('win_status'):
                    squad_game.win_status = True
                squad_game.end_time = timezone.localtime()
                squad_game.save(update_fields=['end_time', 'win_status'])
                # self.wait_for_image(os.path.join(BASE_DIR, 'utils/controls/opponent_select.png'))
                self.fifa_account.refresh_from_db()
                if self.fifa_account.squad_special_game_one is False:
                    new_print(self.fifa_account, 'squad_special_game_one game done')
                    set_sub_log(self.sbc_worker, f'after special game one')
                    # self.fifa_account.squad_special_game_one = True
                elif self.fifa_account.squad_special_game_two is False:
                    new_print(self.fifa_account, 'squad_special_game_two game done')
                    set_sub_log(self.sbc_worker, f'after special game two')
                    # self.fifa_account.squad_special_game_two = True
                else:
                    new_print(self.fifa_account, 'one of none special game done ',
                              self.fifa_account.account_played_games)
                    set_sub_log(self.sbc_worker, f'after game {self.fifa_account.account_played_games}')
                # self.fifa_account.save()
                # self.fifa_account.refresh_from_db()
                new_print(self.fifa_account, 'number of account_played_games = ',
                          self.fifa_account.account_played_games)
                # self.play_football_utils.start_opponent()
                # if self.fifa_account.account_played_games == 4 or self.fifa_account.account_played_games == 8:
                #     time.sleep(10)
                #     self.ps4_buttons.square()
                #     self.get_screen_shot()
                #     if self.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 squad battle')
                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

    # todo : move moments to another class in other file
    def do_moments(self, moment_number=0):
        new_print(self.fifa_account, 'need to do moment : ', moment_number)
        set_sub_log(self.sbc_worker, 'doing moment 0')
        set_sbc_status(self.sbc_worker, 'doing moments')
        self.go_to_state('ultimate_team', 'moments_foundations')
        self.ps4_buttons.cross()

        success = False

        for iiie in range(100):
            self.get_screen_shot()
            check_squad_errors_result = self.play_football_utils.check_squad_errors()
            if check_squad_errors_result == 'continue':
                continue
            elif check_squad_errors_result:
                return check_squad_errors_result
            elif iiie > 20 and iiie % 3 == 0 and (self.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/advance_in_go_squad_battle.png'),
                    'screen_shot_tmp.jpg') or self.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/squad_actions_in_go_squad_battle.png'),
                'screen_shot_tmp.jpg')):
                new_print(self.fifa_account, 'not going to squad battle? press option')
                self.ps4_buttons.option()
                time.sleep(2)
                continue
            new_print(self.fifa_account, 'press cross , until enter moment game')
            self.ps4_buttons.cross()
            time.sleep(1)
            if self.has_image(
                    os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/scoreboard.png'),
                    'screen_shot_tmp.jpg'
            ):
                new_print(self.fifa_account, 'find scoreboard')
                success = True
                break
        if success:
            close_old_connections()
            if moment_number == 0:
                set_sub_log(self.sbc_worker, 'moment game settings setting ...')
                # self.play_football_utils.set_squad_game_settings()
            else:
                new_print(self.fifa_account, 'no need change settings')
            moment_game = FifaAccountMomentsGame.objects.create(
                fifa_account=self.fifa_account,
                moment_number=0
            )
            moment_status = self.complete_10_passing_moment()
            if moment_status.get('win_status'):
                moment_game.win_status = True
                moment_game.save(update_fields=['win_status'])
                # accept reward to back to moments menu
                self.ps4_buttons.cross()
                time.sleep(1)
                self.ps4_buttons.cross()
                time.sleep(5)
                self.ps4_buttons.circle()
                time.sleep(1)
                self.ps4_buttons.circle()
                time.sleep(1)
                self.ps4_buttons.circle()
            new_print(self.fifa_account, 'moments complete , go to clim ')
            # todo : fix navigation system , then mix bellow go_to_state
            self.go_to_state('ultimate_team', 'play')
            self.go_to_state('play', 'moments_star_gallery')
            time.sleep(1)
            self.ps4_buttons.r1()
            time.sleep(1)
            # self.go_to_state('moments_star_gallery', 'star_gallery_seasonal')
            #

            self.ps4_buttons.cross()
            time.sleep(5)
            self.ps4_buttons.cross()
            time.sleep(5)
            self.ps4_buttons.cross()
            time.sleep(5)
            self.ps4_buttons.circle()
            self.ps4_buttons.circle()
            self.ps4_buttons.circle()
            self.ps4_buttons.circle()
            return True
        else:
            new_print(self.fifa_account, 'moments not completed')
            return False

    def complete_10_passing_moment(self):
        new_print(self.fifa_account, 'start moment : 10 pass')
        win_status = False
        for iiie in range(100):
            self.get_screen_shot()
            if self.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, 'find win moments')
                win_status = True
                break
            if iiie and iiie % 20 == 0 and self.just_find_state():
                new_print(self.fifa_account, 'after game , find state , break , ', self.just_find_state())
                break
            self.ps4_buttons.cross()
            time.sleep(1)
            # self.ps4_buttons.press_cross(press_time=1.1)
            # self.ps4_buttons.release_cross(sleep_after=1.1)
        return {'win_status': win_status}

    def play_one_game(self, break_after_game=False, round_count=4):
        must_break = False
        for i in range(round_count):
            if must_break:
                break
            set_sub_log(self.sbc_worker, f'game round {i + 1}')
            count = 0
            while True:
                count += 1
                round_number = self.play_football_utils.get_round_number()
                if count > 90 and round_number == 0:
                    new_print(self.fifa_account, 'can`t get round number')
                    # self.put_on_rest_mode()
                    if self.round == 1:
                        round_number = 2
                    else:
                        round_number = 1
                    # raise Exception('can not find round of game')

                self.get_screen_shot()
                if self.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/reply_squad.png'),
                        'screen_shot_tmp.jpg'):
                    new_print(self.fifa_account, 'reply squad found. will end of play')
                    self.break_press_r1 = True
                    self.release_buttons_after_game()
                    if self.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/confirm_reply_squad.png'),
                            'screen_shot_tmp.jpg'):
                        self.ps4_buttons.up(sleep_after=.5)
                    self.ps4_buttons.cross()
                    time.sleep(2)
                    return
                if self.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 found. will end of play')
                    self.break_press_r1 = True
                    self.release_buttons_after_game()
                    time.sleep(2)
                    return
                if self.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.has_image(
                    os.path.join(
                        BASE_DIR,
                        # todo : image xbox360 added. add xboxs and ps4 images
                        f'utils/{self.fifa_account.platform}_controls/after_squad_game_1.png'),
                    'screen_shot_tmp.jpg') or self.has_image(
                    os.path.join(
                        BASE_DIR,
                        # todo : image xbox360 added. add xboxs and ps4 images
                        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.release_buttons_after_game()
                    time.sleep(1)
                    must_break = True
                    break
                if self.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 selection found')
                    self.break_press_r1 = True
                    self.release_buttons_after_game()
                    time.sleep(1)
                    must_break = True
                    self.ps4_buttons.circle()
                    time.sleep(1)
                    break

                if round_number:
                    break
                self.ps4_buttons.cross()
                time.sleep(1)
            self.round = round_number
            self.break_press_r1 = False
            new_print(self.fifa_account, 'start playing')
            game_result = self.play_football_utils.start_playing()
            new_print(self.fifa_account, f'after round {i + 1}')
            set_sub_log(self.sbc_worker, f'after round {i + 1}')
            if game_result == 'game is done':
                self.break_press_r1 = True
                self.release_buttons_after_game()
                new_print(self.fifa_account, 'end of playing step 1')
                time.sleep(2)
                # time.sleep(2)
                # self.ps4_buttons.cross()
                # time.sleep(3)
                # self.ps4_buttons.cross()
                # time.sleep(5)
                break
            elif game_result == 'game was done':
                new_print(self.fifa_account, 'game was done')
                self.break_press_r1 = True
                self.release_buttons_after_game()
                time.sleep(2)
                return
            # time.sleep(10)
            self.break_press_r1 = True
            self.release_buttons_after_game()
            time.sleep(2)
            new_print(self.fifa_account, 'end of playing step 2')
            # self.ps4_buttons.cross()
            # time.sleep(3)
            # self.ps4_buttons.cross()
        if break_after_game:
            return
        win_status = False

        self.release_buttons_after_game()
        for num in range(100):
            new_print(self.fifa_account, 'try to find opponent select')
            if num > 98:
                new_print(self.fifa_account, 'cant get opponent select')
                # self.put_on_rest_mode()
                raise Exception('after game complete can not find new game')
            self.get_screen_shot()
            if self.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/win_squad_game_sign.png'),
                    'screen_shot_tmp.jpg'):
                new_print(self.fifa_account, 'find win status')
                win_status = True
            if self.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, 'find win moments')
                win_status = True
                break
            if self.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/opponent_select.png'),
                    'screen_shot_tmp.jpg'):
                break
            if self.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/reply_squad.png'),
                'screen_shot_tmp.jpg'):
                new_print(self.fifa_account, 'after game , find reply squad , break')
                break
            if self.just_find_state():
                new_print(self.fifa_account, 'after game , find state , break , ', self.just_find_state())
                break
            self.ps4_buttons.cross()
            time.sleep(3)
        return {'win_status': win_status}

    def xboxs_go_to_app(self, have_to=False, try_counter=0):
        return self.console_login_utils.xboxs_go_to_app(have_to=have_to, try_counter=try_counter)

    def console_close_ultimate(self, need_get_new_sid=True, state='home_main'):
        return self.console_login_utils.console_close_ultimate(need_get_new_sid=need_get_new_sid, state=state)
