import json
import os
import time
import traceback

import telepot
from django.db import close_old_connections
from django.db.models import Q, Subquery, OuterRef, Count, IntegerField, Value
from django.db.models.functions import Coalesce
from django.utils import timezone

from accounts.models import FifaAccountRequest, MuleAccounts, FifaAccountSearch, \
    ConsoleBotSetting, AccountSalablePlayerCard, ItemPack, FifaAccountCurrentItems, CloseWebAppTransfers
from sbc import FIFA_REPORT_TOKEN, ARZBAZI_REPORT_TOPIC_LOGS_THREAD_MESSAGE_ID
from sbc.models import SBCType, SBCProcess, AccountSBCNeedPlayer, SBCFileWorkLog
from sbc.public_methods import new_print, set_sub_log, set_sbc_status, get_trade_pile, \
    delete_sold_items, put_item_for_sale, sell_items, ThreadWithReturnValue, pin_events_creator, \
    clim_lvlup_objectives_milestones, update_account_squad_battle_data, save_sold_items, save_selling_items, \
    print_cache2, set_main_log, save_account_request
from accounts.web_login_utils import logout_login
from sbc.sbc_solver import SBCSolver
from accounts.console_bot_settings import allowed_discharge_time
from sniper.discharge import DischargeRunner
from sniper.models import DischargeMode2, MuleDischargeMode2
from squad_battle import calculate_need_game2, ACCOUNT_ALLOWED_PLAYED_ALL, ACCOUNT_TOO_MANY_UNLISTED_ITEMS3
from squad_battle.models import FifaAccountSquadGame, FifaAccountMomentsGame
from trade import console_trade_quality_dict
from trade.models import ConsoleTradeOneHistory
from utils.ea_settings import fifa_23_address

bot = telepot.Bot(FIFA_REPORT_TOKEN)


# class SquadBattleRunner(SBCSolver, DischargeRunner):
class SquadBattleRunner(DischargeRunner):
    special_squad_players_build_with_position = {
        '178005': [178005, 'GK'], '193082': [193082, 'RB'],
        '253163': [253163, 'CB'], '241486': [241486, 'CB'],
        '202884': [202884, 'LB'], '231443': [231443, 'RM'],
        '241096': [241096, 'CM'], '226161': [226161, 'CM'],
        '190286': [190286, 'LM'], '214997': [214997, 'ST'], '199110': [199110, 'ST'],
    }

    def invest_move_items_to_club(self, try_counter=0):
        set_sub_log(self.sbc_worker, 'invest moving items to club')
        new_print(self.fifa_account, 'invest moving items to club')
        login_result = logout_login(self, self.sbc_worker, self.fifa_account)
        if login_result.get('status_bool') is False:
            if try_counter < 2:
                time.sleep(300)
                close_old_connections()
                return self.invest_move_items_to_club(try_counter=try_counter+1)
            new_print(self.fifa_account, 'invest move items , login result : ', login_result)
            set_sbc_status(self.sbc_worker, 'login failed')
            time.sleep(5 * 60)
            close_old_connections()
            raise Exception(login_result.get('reason'))
        last_trade_history = ConsoleTradeOneHistory.objects.filter(fifa_account=self.fifa_account).last()
        trade_pile_json = get_trade_pile(self.fifa_account, self.se, self.main_dic).json()
        trade_pile_items = trade_pile_json['auctionInfo']
        sold_items_count = 0
        for item_data in trade_pile_items:
            if item_data.get('tradeState', '') == 'closed':
                sold_items_count += 1
        if last_trade_history:
            last_trade_history.refresh_from_db()
            last_trade_history.transfer_list_items_count = len(trade_pile_json.get('auctionInfo', []))
            last_trade_history.sold_items_count += sold_items_count
            last_trade_history.save()
        if not self.fifa_account.console_trade_one_quality:
            new_print(self.fifa_account, 'no quality set , so no work to do. quality : ',
                      self.fifa_account.console_trade_one_quality)
            return
        quality_data_2 = console_trade_quality_dict[self.fifa_account.console_trade_one_quality]
        cant_move_items_1 = []
        move_items_1 = []
        for nnttu in trade_pile_items:
            if nnttu.get('tradeState', '') == 'closed':
                continue
            asset_id = nnttu['itemData']['assetId']
            club_id = nnttu['itemData']['id']
            rating = nnttu['itemData']['rating']
            rare_flag = nnttu['itemData']['rareflag']
            last_sale_price = nnttu['itemData'].get('lastSalePrice', 0)
            market_min_price = nnttu['itemData'].get('marketDataMinPrice', 2000)
            if (
                    self.fifa_account.console_trade_one_quality in [
                'bronze1', 'silver0', 'silver1', 'gold0', 'gold1'] and
                    nnttu['itemData']['itemType'] == 'player' and
                    last_sale_price and
                    quality_data_2[0] <= rating <= quality_data_2[1] and
                    rare_flag == quality_data_2[2] and
                    1 < last_sale_price < 1000
            # ) or (
            #         self.fifa_account.console_trade_one_quality == 'position_modifier' and
            #         nnttu['itemData']['itemType'] == 'training' and
            #         nnttu['itemData']['resourceId'] == 5003181
            ):
                data_6 = {"itemData": [{"id": club_id, "pile": "club"}]}
                move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_6), 0)
                save_account_request(
                    fifa_account=self.fifa_account,
                    link=f'{fifa_23_address}/item/pile_club',
                )
                try:
                    move_result_json = move_result.json()
                    if move_result_json.get('itemData', [{}])[0].get('success', False) is True:
                        move_items_1.append(move_result_json)
                    else:
                        cant_move_items_1.append(club_id)
                        new_print(self.fifa_account, 'error on move 10 : ', move_result.text,
                                  ' asset_id : ', asset_id, ' rare : ', rare_flag,
                                  'last sale price : ', last_sale_price)
                except:
                    cant_move_items_1.append(club_id)
                    new_print(self.fifa_account, 'move result 10 error : ', move_result.text)
                time.sleep(2)
        new_print(self.fifa_account, 'move unassign to transfer list')
        unassigned_items = self.get_items().json()['itemData']
        for nnttm in unassigned_items:
            item_id = nnttm['id']
            data_1 = {"itemData": [{"id": item_id, "pile": "trade"}]}
            move_result_2 = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_1), 0)
            save_account_request(
                fifa_account=self.fifa_account,
                link=f'{fifa_23_address}/item/pile_trade',
            )
            asset_id = nnttm['assetId']
            item_rating = nnttm.get('rating', 0)
            item_rare_flag = nnttm.get('rareflag', 0)
            last_sale_price = nnttm.get('lastSalePrice', 0)
            item_type = nnttm.get('itemType')
            discard_value = nnttm.get('discardValue')
            if (nnttm.get('untradeable') is False and self.fifa_account.console_trade_one_quality in [
                'bronze1', 'silver0', 'silver1', 'gold0', 'gold1'] and
                    item_type == 'player' and
                    last_sale_price and
                    quality_data_2[0] <= item_rating <= quality_data_2[1] and
                    item_rare_flag == quality_data_2[2] and
                    1 < last_sale_price < 1000
            ):
                data_6 = {"itemData": [{"id": item_id, "pile": "club"}]}
                move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_6), 0)
                save_account_request(
                    fifa_account=self.fifa_account,
                    link=f'{fifa_23_address}/item/pile_club',
                )
                try:
                    move_result_json = move_result.json()
                    if move_result_json.get('itemData', [{}])[0].get('success', False) is True:
                        move_items_1.append(move_result_json)
                    else:
                        cant_move_items_1.append(item_id)
                        new_print(self.fifa_account, 'error on move 11 : ', move_result.text)
                except:
                    cant_move_items_1.append(item_id)
                    new_print(self.fifa_account, 'move result 11 error : ', move_result.text)
                time.sleep(2)
                continue
            if nnttm.get('untradeable') is False:
                try:
                    save_selling_items(
                        self.fifa_account,
                        item_id=item_id,
                        buy_price=last_sale_price or 0,
                        rating=item_rating,
                        rare=item_rare_flag or 0,
                        asset_id=asset_id or 0,
                        item_type=item_type,
                        discard_value=discard_value or 0,
                    )
                except:
                    new_print(self.fifa_account, 'save selling items error 2 : ', traceback.format_exc())
            try:
                move_result_json = move_result_2.json()
                if move_result_json.get('itemData', [{}])[0].get('success', False) is True:
                    move_items_1.append(move_result_json)
                else:
                    cant_move_items_1.append(item_id)
                    new_print(self.fifa_account, 'error on move 12 : ', move_result_2.text)
            except:
                cant_move_items_1.append(item_id)
                new_print(self.fifa_account, 'move result 12 error : ', move_result_2.text)
            time.sleep(2)
        if last_trade_history:
            last_trade_history.unassigned_item_count = len(unassigned_items)
            last_trade_history.save(update_fields=['unassigned_item_count'])
        new_print(self.fifa_account, 'invest move items to club result : ', move_items_1)
        try:
            save_sold_items(self.fifa_account, trade_pile_json)
        except:
            new_print(self.fifa_account, 'cant save sold items : ', traceback.format_exc())
        delete_sold_items(self.se, self.main_dic['header'])

    def squad_battle_handler_web_app(self, need_fix_main_squad=False, use_contract=True):

        try:
            new_print(self.fifa_account,
                      'start bot in squad battle server side handler ,'
                      ' need_fix_main_squad : ', need_fix_main_squad,
                      ' use_contract : ', use_contract,
                      )
            set_sbc_status(self.sbc_worker, 'squad server side ...')
            # self.sbc_worker.refresh_from_db()
            # self.sbc_worker.status = 'squad server side ...'
            # self.sbc_worker.status_change_time = timezone.localtime()
            # self.sbc_worker.save()

            try_update_credit = 0
            try_clim_squad_prize = 0
            try_preview_gold_pack = 0
            try_open_free_packs = 0
            try_delete_sold_items = 0
            try_sell_items = 0
            need_contracts_count = 0
            need_manager_contracts_count = 0
            need_heals_count = 0
            need_position_modifier = 0
            need_player_for_special_squad = []
            for nm in range(12):
                # bellow break for manual break loop
                # worker.refresh_from_db()
                # if worker.has_error:
                #     new_print(self.fifa_account, 'worker has error , break it.')
                #     break

                if self.sbc_worker.must_done:
                    new_print(self.fifa_account, 'worker must stop , break it.')
                    break

                login_status = logout_login(self, self.sbc_worker, self.fifa_account)
                if login_status.get('status_bool') is False:
                    if login_status.get('reason') == 'console login':
                        raise Exception('console login')
                    else:
                        new_print(self.fifa_account, 'error in login : , ', login_status)
                        set_sbc_status(self.sbc_worker, 'login failed')
                # if login_status and str(login_status).startswith('Traceback'):
                #     new_print(self.fifa_account, 'error in login : , ', traceback.format_exc())
                #     set_sbc_status(self.sbc_worker, 'login failed')
                # if login_status == 'console login':
                #     raise Exception('console login')
                time.sleep(2)
                if try_update_credit < 2:
                    try:
                        self.update_credit()
                        try_update_credit += 2
                    except:
                        new_print(self.fifa_account, 'update credit error : ', traceback.format_exc())
                        try_update_credit += 1
                        continue
                time.sleep(2)
                if try_clim_squad_prize < 2:
                    try:
                        # clim squad battle reward
                        resp = self.se.post(
                            f'{fifa_23_address}/sqbt/user/prize',
                            headers=self.main_dic['header'])
                        new_print(self.fifa_account, 'sqbt content = ', resp.text)
                        try_clim_squad_prize += 2
                    except:
                        new_print(self.fifa_account, 'error 22 : ', traceback.format_exc())
                        try_clim_squad_prize += 1
                        continue

                try:
                    set_sbc_status(self.sbc_worker, 'clim objectives and milestones ...')
                    clim_count_in_24_hour = FifaAccountRequest.objects.using('logs_pgbouncer').filter(
                        fifa_account=self.fifa_account,
                        link=f'{fifa_23_address}/scmp/campaign?type=active',
                        create_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                    ).count()
                    if clim_count_in_24_hour < 1:
                        # clim objectives and milestones
                        pin_events_creator(
                            fifa_account=self.fifa_account,
                            se=self.se, persona_id=self.fifa_account.persona_id,
                            nucleus_id=self.fifa_account.nucleus_id,
                            source="Objectives - Season Progress", sid=self.sid,
                            counter=self.get_pin_events_counter())
                        clim_lvlup_objectives_milestones(
                            self.fifa_account, self.se, self.main_dic['header'], self.fcas_sid,
                        )
                        time.sleep(2)
                        sell_items(self, self.sbc_worker, self.fifa_account)
                    else:
                        new_print(self.fifa_account, f'climed in 24 hour {clim_count_in_24_hour}')

                except:
                    new_print(self.fifa_account, 'error 21 : ', traceback.format_exc())
                # open preview gold pack
                if try_preview_gold_pack < 2 and FifaAccountRequest.objects.using('logs_pgbouncer').filter(
                        fifa_account=self.fifa_account,
                        link=f'{fifa_23_address}/preview/pack/10301/items',
                        create_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                ).count() < 1:
                    try:
                        self.preview_and_open_good_gold_pack()
                        try_preview_gold_pack += 2
                    except:
                        new_print(self.fifa_account, 'can not open gold pack error : ', traceback.format_exc())
                        try_preview_gold_pack += 1
                        continue
                time.sleep(2)
                if try_open_free_packs < 2:
                    # open all free packs ( all packs reward )
                    try:
                        resp = self.se.get(
                            f'{fifa_23_address}/store/purchaseGroup/cardpack?ppInfo=true',
                            headers=self.main_dic['header'])
                        json_resp = resp.json()
                        packs = json_resp['purchase']
                        try_open_free_packs += 2
                    except:
                        new_print(self.fifa_account, 'open pack has error : ', traceback.format_exc())
                        packs = []
                        try_open_free_packs += 1
                        continue
                    time.sleep(2)
                    sell_items_result = sell_items(self, self.sbc_worker, self.fifa_account, update_trade_pile=True)
                    set_sbc_status(self.sbc_worker, 'open packs', update_time=False)
                    for pack in packs:
                        if pack['coins'] == 0:
                            len_trade_pile = len(sell_items_result.get('trade_pile_auction', []))
                            new_print(self.fifa_account, 'trade pile : ', len_trade_pile,
                                      ' pack id : ', pack['id'])
                            if len_trade_pile > 85 and pack.get('untradeable', True) is False:
                                new_print(self.fifa_account, 'trade pile more than allowed 3. continue')
                                continue
                            try:
                                new_print(self.fifa_account, 'pack id', pack['id'], 'will open')
                                open_pack_resp = self.open_pack(pack['id'])
                                pack_items = []
                                try:
                                    pack_items = open_pack_resp.json()['itemList']
                                except:
                                    new_print(self.fifa_account,
                                              'open pack in squad battle server handler, pack id : ', pack['id'],
                                              ' opened data : ', open_pack_resp.text, '\nerror: ',
                                              traceback.format_exc())
                                pack_price = self.calculate_pack_price(pack_items=pack_items)
                                ItemPack.objects.create(
                                    fifa_account=self.fifa_account,
                                    pack_id=pack['id'],
                                    open_price=0,
                                    pack_value=pack_price,
                                )
                                time.sleep(2)
                                # delete_sold_items(self.se, self.main_dic['header'], self.server_key)
                                # time.sleep(2)
                                sell_items_result = sell_items(self, self.sbc_worker, self.fifa_account,
                                                               check_transfer_list=False, update_trade_pile=True)
                            except:
                                new_print(self.fifa_account, 'error on open pack squad handler',
                                          traceback.format_exc())

                # read squad battle data
                try:
                    new_print(self.fifa_account, 'updating squad battle data')
                    update_account_squad_battle_data(self.fifa_account, self.se,
                                                     self.main_dic['header'])
                except:
                    new_print(self.fifa_account, 'error on read squad battle data : ', traceback.format_exc())
                # squad build handle
                try:
                    if need_fix_main_squad == 1:
                        self.active_squad_handler(use_contract=use_contract)
                    elif need_fix_main_squad == 2:
                        self.active_squad_handler(use_contract=use_contract, change_manager=True)
                        need_fix_main_squad = 1
                    else:
                        new_print(self.fifa_account,
                                  'allowed games done or not need fix main squad. no need to handle active squad')
                except:
                    new_print(self.fifa_account, 'error on active squad handler', traceback.format_exc())

                need_contracts_count = self.need_contracts
                need_manager_contracts_count = self.manager_need_contracts
                need_heals_count = self.need_heals
                need_position_modifier = self.need_position_change
                need_player_for_special_squad = self.need_players_for_special_squad

                time.sleep(2)
                # if try_delete_sold_items < 2:
                #     try:
                #         delete_sold_items(self.se, self.main_dic['header'], self.server_key)
                #         time.sleep(2)
                #         try_delete_sold_items += 2
                #     except:
                #         new_print(self.fifa_account, 'error on delete sold items . error : ',
                #                   traceback.format_exc())
                #         try_delete_sold_items += 1
                #         continue
                if try_sell_items < 2:
                    try:
                        sell_items(self, self.sbc_worker, self.fifa_account, sell_club_players=True)
                        try_sell_items += 2
                    except:
                        new_print(self.fifa_account, 'error sell items squad handler . error : ',
                                  traceback.format_exc())
                        try_sell_items += 1
                        continue
                break
            return {'status': 'success',
                    'need_contracts_count': need_contracts_count,
                    'need_manager_contracts_count': need_manager_contracts_count,
                    'need_heals_count': need_heals_count,
                    'need_position_modifier': need_position_modifier,
                    'need_player_for_special_squad': need_player_for_special_squad,
                    }

        except Exception as error:
            return {'status': 'failed', 'error': error, 'traceback': traceback.format_exc()}

    def squad_battle_handler(self, need_fix_main_squad=0):
        if self.fifa_account.is_running_console_trade_one or self.fifa_account.run_console_invest_trade_one:
            self.invest_move_items_to_club()
        set_sub_log(self.sbc_worker, 'web app side started ...')
        new_print(self.fifa_account, 'run web app handler')

        use_first_contract = False if (self.fifa_account.use_special_squad and
                                       not self.fifa_account.special_squad_ready_to_play) else True
        thread_1 = ThreadWithReturnValue(target=self.squad_battle_handler_web_app,
                                         kwargs={'need_fix_main_squad': need_fix_main_squad,
                                                 'use_contract': use_first_contract})
        close_old_connections()
        thread_1.start()
        while thread_1.is_alive():
            self.public_moves.ps4_buttons.right()
            time.sleep(1)
            self.public_moves.ps4_buttons.left()
            time.sleep(100)
        result = thread_1.join() or {}
        if result.get('status') == 'success':
            new_print(self.fifa_account, 'squad battle bot result : ', result)
            self.sbc_worker.refresh_from_db()
            if self.sbc_worker.has_error and self.sbc_worker.status == 'login failed':
                raise Exception('LOGIN WEB APP FAILED')
            if self.fifa_account.run_squad_battle:
                if result.get('need_contracts_count'):
                    set_sub_log(self.sbc_worker, f'start buy contract {result.get("need_contracts_count")}')
                    set_sbc_status(self.sbc_worker, 'buying contract ...')
                    self.public_moves.buy_contract(result.get('need_contracts_count'))
                    self.need_contracts = 0
                if result.get('need_manager_contracts_count'):
                    set_sub_log(self.sbc_worker,
                                f'start buy manager contract {result.get("need_manager_contracts_count")}')
                    set_sbc_status(self.sbc_worker, 'buying manger contract ...')
                    self.public_moves.buy_contract(
                        result.get('need_manager_contracts_count'), manager=True)
                    self.manager_need_contracts = 0
                if result.get("need_heals_count"):
                    set_sub_log(self.sbc_worker, f'start buy heals {result.get("need_heals_count")}')
                    set_sbc_status(self.sbc_worker, 'buying heals ...')
                    self.public_moves.buy_healing(result.get("need_heals_count"))
                    self.need_heals = 0
                if result.get("need_position_modifier"):
                    new_print(self.fifa_account, 'really need it??', result.get("need_position_modifier"))
                    # set_sub_log(self.sbc_worker,
                    #             f'start buy position modifier {result.get("need_position_modifier")}')
                    # set_sbc_status(self.sbc_worker, 'buying position modifier ...')
                    # self.public_moves.buy_position_modifier(result.get("need_position_modifier"))
                    # self.need_position_change = 0
                if result.get("need_player_for_special_squad") and self.fifa_account.use_special_squad:
                    set_sub_log(self.sbc_worker, f'start buy players for special squad')
                    set_sbc_status(self.sbc_worker, 'buying players for special squad ...')
                    for player_item in result.get("need_player_for_special_squad", []):
                        self.fifa_account.refresh_from_db()
                        if (self.fifa_account.credit - player_item.price > 10000 and
                                self.fifa_account.fifaaccountsquadgame_set.count() > 20):
                            # position = self.special_squad_players_build_with_position.get(player_item.asset_id)
                            # target_filter = SBCTargetFilter(position=position, buy_now_price=player_item.price)
                            self.public_moves.console_search_player_and_bid(
                                player=player_item,
                                # sbc_price=player_item.price,
                                # target_filter=target_filter,
                                # use_target_and_filter=True,
                            )
                    self.need_players_for_special_squad = []

            if AccountSalablePlayerCard.objects.filter(fifa_account=self.fifa_account):
                set_sub_log(self.sbc_worker, f'sell items staring ...')
                set_sbc_status(self.sbc_worker, 'selling items ...')
                self.console_transfer_list_sell_items(need_get_new_sid=False)
        else:
            new_print(self.fifa_account, 'handler has error.', result.get('status'))
        if result.get('status') == 'success' and (
                result.get('need_heals_count') or
                result.get('need_contracts_count') > 0 or
                result.get('need_manager_contracts_count') > 0 or
                result.get('need_position_modifier') > 0 or
                len(result.get('need_player_for_special_squad', [])) > 0 or
                use_first_contract == 0):
            new_print(self.fifa_account, 'need apply heals : ', result.get('need_heals_count'),
                      'need apply contract : ', result.get('need_contracts_count'),
                      'need apply manager contract : ', result.get('need_manager_contracts_count'),
                      'need apply position change : ', result.get('need_position_modifier'),
                      'need player for special squad : ', len(result.get('need_player_for_special_squad')))
            self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
            thread_2 = ThreadWithReturnValue(target=self.squad_battle_handler_web_app)
            close_old_connections()
            thread_2.start()
            while thread_2.is_alive():
                # todo : remove this print and close old connection to reduce database connections
                # new_print(self.fifa_account, 'waiting sbc solver end , pressing left and right')
                self.public_moves.ps4_buttons.right()
                time.sleep(1)
                self.public_moves.ps4_buttons.left()
                time.sleep(100)
            result_2 = thread_2.join() or {}
            if result_2.get('status') == 'success':
                c_count = result.get('need_contracts_count')
                if c_count:
                    set_sub_log(self.sbc_worker, f'start buy contract {c_count}')
                    set_sbc_status(self.sbc_worker, 'buying contract ...')
                    self.public_moves.buy_contract(int(c_count))
                    self.need_contracts = 0
                m_c_count = result.get('need_manager_contracts_count')
                if m_c_count:
                    set_sub_log(self.sbc_worker,
                                f'start buy manager contract {m_c_count}')
                    set_sbc_status(self.sbc_worker, 'buying manger contract ...')
                    self.public_moves.buy_contract(int(m_c_count), manager=True)
                    self.manager_need_contracts = 0
                h_count = result.get('need_heals_count')
                if h_count:
                    set_sub_log(self.sbc_worker, f'start buy heals {h_count}')
                    set_sbc_status(self.sbc_worker, 'buying heals ...')
                    self.public_moves.buy_healing(int(h_count))
                    self.need_heals = 0
                n_poisiton = result.get('need_position_modifier')
                if n_poisiton:
                    new_print(self.fifa_account, 'need position modifier? HOW ?!!')
                n_player_special = result.get('need_player_for_special_squad', [])
                if n_player_special and len(n_player_special) > 0:
                    set_sub_log(self.sbc_worker, f'start buy players for special squad')
                    set_sbc_status(self.sbc_worker, 'buying players for special squad ...')
                    for player_item in n_player_special:
                        self.fifa_account.refresh_from_db()
                        if self.fifa_account.credit - player_item.price > 7000:
                            self.public_moves.console_search_player_and_bid(
                                player=player_item,
                                sbc_price=player_item.price,
                            )
                if c_count > 0 or m_c_count > 0 or h_count > 0 or len(n_player_special) > 0:
                    self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                    thread_3 = ThreadWithReturnValue(target=self.squad_battle_handler_web_app)
                    close_old_connections()
                    thread_3.start()
                    while thread_3.is_alive():
                        # todo : remove this print and close old connection to reduce database connections
                        # new_print(self.fifa_account, 'waiting sbc solver end , pressing left and right')
                        self.public_moves.ps4_buttons.right()
                        time.sleep(1)
                        self.public_moves.ps4_buttons.left()
                        time.sleep(100)
                    result_3 = thread_3.join() or {}
                    if result_3.get('status') == 'success':
                        new_print(self.fifa_account, 'thread_3 done.')
                    else:
                        new_print(self.fifa_account, 'thread_3 has error.')

        set_sub_log(self.sbc_worker, 'web app handler done')
        new_print(self.fifa_account, 'web app handler done')


    # def run_web_app_handler(self, need_fix_main_squad=0):
    #     if self.fifa_account.is_running_console_trade_one or self.fifa_account.run_console_invest_trade_one:
    #         self.invest_move_items_to_club()
    #     set_sub_log(self.sbc_worker, 'web app side started ...')
    #     new_print(self.fifa_account, 'run web app handler')
    #     handler_worker = SquadBattleServerSideHandlerWorker.objects.filter(
    #         fifa_account=self.fifa_account,
    #         sbc_worker=self.sbc_worker,
    #         is_done=0
    #     ).last()
    #     use_first_contract = 0 if (self.fifa_account.use_special_squad and
    #                                not self.fifa_account.special_squad_ready_to_play) else 1
    #     if not handler_worker or handler_worker.create_time < timezone.localtime() - timezone.timedelta(
    #             seconds=60 * 15):
    #         handler_worker = SquadBattleServerSideHandlerWorker.objects.create(
    #             fifa_account=self.fifa_account,
    #             sbc_worker=self.sbc_worker,
    #             need_fix_main_squad=need_fix_main_squad,
    #             use_contract=use_first_contract
    #         )
    #     for num in range(60 * 60):
    #         handler_worker.refresh_from_db()
    #         self.sbc_worker.refresh_from_db()
    #         if self.sbc_worker.has_error and self.sbc_worker.status == 'login failed':
    #             raise Exception('LOGIN WEB APP FAILED')
    #         if handler_worker.is_done:
    #             if self.fifa_account.run_squad_battle:
    #                 if handler_worker.need_contracts_count:
    #                     set_sub_log(self.sbc_worker, f'start buy contract {handler_worker.need_contracts_count}')
    #                     set_sbc_status(self.sbc_worker, 'buying contract ...')
    #                     self.public_moves.buy_contract(handler_worker.need_contracts_count)
    #                     self.need_contracts = 0
    #                 if handler_worker.need_manager_contracts_count:
    #                     set_sub_log(self.sbc_worker,
    #                                 f'start buy manager contract {handler_worker.need_manager_contracts_count}')
    #                     set_sbc_status(self.sbc_worker, 'buying manger contract ...')
    #                     self.public_moves.buy_contract(
    #                         handler_worker.need_manager_contracts_count, manager=True)
    #                     self.manager_need_contracts = 0
    #                 if handler_worker.need_heals_count:
    #                     set_sub_log(self.sbc_worker, f'start buy heals {handler_worker.need_heals_count}')
    #                     set_sbc_status(self.sbc_worker, 'buying heals ...')
    #                     self.public_moves.buy_healing(handler_worker.need_heals_count)
    #                     self.need_heals = 0
    #                 if handler_worker.need_position_modifier:
    #                     new_print(self.fifa_account, 'really need it??', handler_worker.need_position_modifier)
    #                     # set_sub_log(self.sbc_worker,
    #                     #             f'start buy position modifier {handler_worker.need_position_modifier}')
    #                     # set_sbc_status(self.sbc_worker, 'buying position modifier ...')
    #                     # self.public_moves.buy_position_modifier(handler_worker.need_position_modifier)
    #                     # self.need_position_change = 0
    #                 if handler_worker.need_player_for_special_squad and self.fifa_account.use_special_squad:
    #                     set_sub_log(self.sbc_worker, f'start buy players for special squad')
    #                     set_sbc_status(self.sbc_worker, 'buying players for special squad ...')
    #                     for player_item in handler_worker.need_player_for_special_squad.all():
    #                         self.fifa_account.refresh_from_db()
    #                         if (self.fifa_account.credit - player_item.price > 10000 and
    #                                 self.fifa_account.fifaaccountsquadgame_set.count() > 20):
    #                             # position = self.special_squad_players_build_with_position.get(player_item.asset_id)
    #                             # target_filter = SBCTargetFilter(position=position, buy_now_price=player_item.price)
    #                             self.public_moves.console_search_player_and_bid(
    #                                 player=player_item,
    #                                 # sbc_price=player_item.price,
    #                                 # target_filter=target_filter,
    #                                 # use_target_and_filter=True,
    #                             )
    #
    #             if AccountSalablePlayerCard.objects.filter(fifa_account=self.fifa_account):
    #                 set_sub_log(self.sbc_worker, f'sell items staring ...')
    #                 set_sbc_status(self.sbc_worker, 'selling items ...')
    #                 self.console_transfer_list_sell_items(need_get_new_sid=False)
    #             # if self.fifa_account.credit > 40000 and self.fifa_account.run_discharge:
    #             #     try:
    #             #         set_sub_log(self.sbc_worker, f'discharge start ...')
    #             #         self.discharge_with_snipe(self.fifa_account.credit, sell_all=True)
    #             #         set_sub_log(self.sbc_worker, f'discharge end ...')
    #             #     except:
    #             #         new_print(self.fifa_account, 'exception in discharge with snipe :   ', traceback.format_exc())
    #             break
    #         elif handler_worker.has_error:
    #             new_print(self.fifa_account, 'handler has error.')
    #             break
    #         else:
    #             new_print(self.fifa_account, 'wait for handler1 done.')
    #             self.public_moves.ps4_buttons.right()
    #             time.sleep(1)
    #             self.public_moves.ps4_buttons.left()
    #             time.sleep(10)
    #     handler_worker.refresh_from_db()
    #     if (handler_worker.need_heals_count > 0 or
    #         handler_worker.need_contracts_count > 0 or
    #         handler_worker.need_manager_contracts_count > 0 or
    #         handler_worker.need_position_modifier > 0 or
    #         handler_worker.need_player_for_special_squad.count() > 0 or
    #         use_first_contract == 0
    #     ) and handler_worker.has_error is False:
    #         new_print(self.fifa_account, 'need apply heals : ', handler_worker.need_heals_count,
    #                   'need apply contract : ', handler_worker.need_contracts_count,
    #                   'need apply manager contract : ', handler_worker.need_manager_contracts_count,
    #                   'need apply position change : ', handler_worker.need_position_modifier,
    #                   'need player for special squad : ', handler_worker.need_player_for_special_squad.count())
    #         self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
    #         handler_worker2 = SquadBattleServerSideHandlerWorker.objects.filter(
    #             fifa_account=self.fifa_account,
    #             sbc_worker=self.sbc_worker,
    #             is_done=0
    #         ).last()
    #         if not handler_worker2 or handler_worker2.create_time < timezone.localtime() - timezone.timedelta(
    #                 seconds=60 * 15):
    #             handler_worker2 = SquadBattleServerSideHandlerWorker.objects.create(
    #                 fifa_account=self.fifa_account,
    #                 sbc_worker=self.sbc_worker,
    #                 need_fix_main_squad=need_fix_main_squad,
    #             )
    #         for num2 in range(60 * 60):
    #             handler_worker2.refresh_from_db()
    #             if handler_worker2.is_done:
    #                 if self.fifa_account.run_squad_battle:
    #                     if handler_worker2.need_contracts_count:
    #                         set_sub_log(self.sbc_worker, f'start buy contract {handler_worker2.need_contracts_count}')
    #                         set_sbc_status(self.sbc_worker, 'buying contract ...')
    #                         self.public_moves.buy_contract(handler_worker2.need_contracts_count)
    #                         self.need_contracts = 0
    #                     if handler_worker2.need_manager_contracts_count:
    #                         set_sub_log(self.sbc_worker,
    #                                     f'start buy manager contract {handler_worker2.need_manager_contracts_count}')
    #                         set_sbc_status(self.sbc_worker, 'buying manger contract ...')
    #                         self.public_moves.buy_contract(
    #                             handler_worker2.need_manager_contracts_count, manager=True)
    #                         self.manager_need_contracts = 0
    #                     if handler_worker2.need_heals_count:
    #                         set_sub_log(self.sbc_worker, f'start buy heals {handler_worker2.need_heals_count}')
    #                         set_sbc_status(self.sbc_worker, 'buying heals ...')
    #                         self.public_moves.buy_healing(handler_worker2.need_heals_count)
    #                         self.need_heals = 0
    #                     if handler_worker2.need_position_modifier:
    #                         new_print(self.fifa_account, 'really need it??', handler_worker.need_position_modifier)
    #                         # set_sub_log(self.sbc_worker,
    #                         #             f'start buy position modifier {handler_worker.need_position_modifier + 1}')
    #                         # set_sbc_status(self.sbc_worker, 'buying position modifier ...')
    #                         # self.public_moves.buy_position_modifier(handler_worker.need_position_modifier + 1)
    #                         # self.need_position_change = 0
    #                     if handler_worker2.need_player_for_special_squad and self.fifa_account.use_special_squad:
    #                         set_sub_log(self.sbc_worker, f'start buy players for special squad')
    #                         set_sbc_status(self.sbc_worker, 'buying players for special squad ...')
    #                         for player_item in handler_worker2.need_player_for_special_squad.all():
    #                             self.fifa_account.refresh_from_db()
    #                             if self.fifa_account.credit - player_item.price > 7000:
    #                                 self.public_moves.console_search_player_and_bid(
    #                                     player=player_item,
    #                                     sbc_price=player_item.price,
    #                                 )
    #                 break
    #             elif handler_worker2.has_error:
    #                 new_print(self.fifa_account, 'handler2 has error')
    #                 break
    #             else:
    #                 self.public_moves.ps4_buttons.right()
    #                 time.sleep(1)
    #                 self.public_moves.ps4_buttons.left()
    #                 new_print(self.fifa_account, 'wait for handler2 done.')
    #                 time.sleep(20)
    #         handler_worker2.refresh_from_db()
    #         if (handler_worker2.need_heals_count > 0 or
    #             handler_worker2.need_contracts_count > 0 or
    #             handler_worker2.need_manager_contracts_count > 0 or
    #             handler_worker.need_position_modifier > 0 or
    #             handler_worker2.need_player_for_special_squad.count() > 0
    #         ) and handler_worker2.has_error is False:
    #             new_print(self.fifa_account, 'need apply heals : ', handler_worker2.need_heals_count,
    #                       'need apply contract : ', handler_worker2.need_contracts_count,
    #                       'need apply manager contract : ', handler_worker2.need_manager_contracts_count,
    #                       'need apply position change : ', handler_worker2.need_position_modifier,
    #                       'need player for special squad : ', handler_worker2.need_player_for_special_squad.count())
    #             self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
    #             handler_worker3 = SquadBattleServerSideHandlerWorker.objects.filter(
    #                 fifa_account=self.fifa_account,
    #                 sbc_worker=self.sbc_worker,
    #                 is_done=0
    #             ).last()
    #             if not handler_worker3 or handler_worker3.create_time < timezone.localtime() - timezone.timedelta(
    #                     seconds=60 * 15):
    #                 handler_worker3 = SquadBattleServerSideHandlerWorker.objects.create(
    #                     fifa_account=self.fifa_account,
    #                     sbc_worker=self.sbc_worker,
    #                     need_fix_main_squad=need_fix_main_squad,
    #                 )
    #             for num3 in range(60 * 60):
    #                 handler_worker3.refresh_from_db()
    #                 if handler_worker3.is_done:
    #                     new_print(self.fifa_account, 'handler3 done.')
    #                     break
    #                 elif handler_worker3.has_error:
    #                     new_print(self.fifa_account, 'handler3 has error.')
    #                     break
    #                 else:
    #                     self.public_moves.ps4_buttons.right()
    #                     time.sleep(1)
    #                     self.public_moves.ps4_buttons.left()
    #                     new_print(self.fifa_account, 'wait for handler3 done.')
    #                     time.sleep(20)
    #                 # if num3 > 58:
    #                 #     new_print(self.fifa_account, 'handler3 not response. continue work.')
    #
    #     set_sub_log(self.sbc_worker, 'web app handler done')
    #     new_print(self.fifa_account, 'web app handler done')

    def solve_sbc_web_app_2(self):
        try:
            new_print(self.fifa_account, 'solve_sbc_web_app_2 started ...')
            if self.fifa_account.is_running_console_trade_one or self.fifa_account.run_console_invest_trade_one:
                self.invest_move_items_to_club()
            AccountSBCNeedPlayer.objects.filter(fifa_account=self.fifa_account).delete()
            sbc_solver = SBCSolver(
                self.sbc_worker.id, self.fifa_account.id,
                self.fifa_account.user_name, self.fifa_account.password,
                self.fifa_account.platform, running_platform='console',
                manual_loyal=False, use_public_moves=False)
            login_result = logout_login(sbc_solver, sbc_worker=self.sbc_worker, fifa_account=self.fifa_account)
            if login_result.get('status_bool') is False:
                new_print(self.fifa_account, 'login error : ', login_result)
                raise Exception(login_result.get('reason'))
            result = sbc_solver.sbc_solver_core()
            new_print(self.fifa_account, 'sbc core result : ', result)
            if result in ['all sbc completed', 'no credit', 'must done']:
                if result in ['no credit', 'must done']:
                    sell_items(sbc_solver, self.sbc_worker, self.fifa_account, sell_club_players=False)
                else:
                    sell_items(sbc_solver, self.sbc_worker, self.fifa_account, sell_club_players=True)
            close_old_connections()
            return result
        except:
            try:
                new_print(self.fifa_account, 'exception error 114 : ', traceback.format_exc())
            except:
                print('error : ', traceback.format_exc())
            close_old_connections()
            time.sleep(20)

    def sbc_solver_func(self):
        set_sub_log(self.sbc_worker, 'sbc solver web app handler start 2')
        new_print(self.fifa_account, 'sbc solver web app handler start ... 2')
        set_sbc_status(self.sbc_worker, 'sbc solver running ...')
        self.public_moves.console_open_ultimate(state_set='home_main', have_to=True)
        # if self.fifa_account.is_running_console_trade_one or self.fifa_account.run_console_invest_trade_one:
        #     self.invest_move_items_to_club()
        # AccountSBCNeedPlayer.objects.filter(fifa_account=self.fifa_account).delete()
        # sbc_solver = SBCSolver(
        #     self.sbc_worker.id, self.fifa_account.id,
        #     self.fifa_account.user_name, self.fifa_account.password,
        #     self.fifa_account.platform, running_platform='console',
        #     manual_loyal=False, use_public_moves=False)
        # logout_login(sbc_solver, sbc_worker=self.sbc_worker, fifa_account=self.fifa_account)
        # result = sbc_solver.sbc_solver_core()
        for iin in range(2):
            thread_1 = ThreadWithReturnValue(target=self.solve_sbc_web_app_2)
            close_old_connections()
            thread_1.start()
            while thread_1.is_alive():
                # todo : remove this print and close old connection to reduce database connections
                # new_print(self.fifa_account, 'waiting sbc solver end , pressing left and right')
                self.public_moves.ps4_buttons.right()
                time.sleep(1)
                self.public_moves.ps4_buttons.left()
                time.sleep(100)
            result = thread_1.join()
            new_print(self.fifa_account, 'sbc solver result : ', result)
            if result in ['all sbc completed', 'no credit']:
                if AccountSalablePlayerCard.objects.filter(fifa_account=self.fifa_account):
                    new_print(self.fifa_account, 'selling items in console start. sbc core status : ', result)
                    set_sub_log(self.sbc_worker, f'sell items 2 staring ...')
                    set_sbc_status(self.sbc_worker, 'selling items 2 ...')
                    self.console_transfer_list_sell_items(need_get_new_sid=False)
                else:
                    new_print(self.fifa_account, 'sbc completed but no item for sell')
                break
            else:
                some_items_bought = False
                # if AccountSBCNeedPlayer.objects.filter(fifa_account=self.fifa_account):
                #     some_items_bought = True
                temp_counter = 0
                for target in AccountSBCNeedPlayer.objects.filter(fifa_account=self.fifa_account):
                    temp_counter += 1
                    new_print(self.fifa_account, 'buying sbc players : ', target, ' temp counter ', temp_counter)
                    if temp_counter % 3 == 0:
                        set_sbc_status(self.sbc_worker, 'buying sbc players')
                    else:
                        set_sbc_status(self.sbc_worker, 'buying sbc players', update_time=False)
                    # todo : if accounts items go upper than 200 , bellow range(1) can be range(2).
                    #  now reduce to 1 because too many items need to buy and it burn too many time
                    for iii in range(1):
                        target_buy_price = 0
                        if target.sbc_target:
                            buy_result = self.public_moves.console_search_player_and_bid(
                                target.sbc_target.player,
                                target_filter=target.sbc_target.target_filter,
                                sbc_price=target.sbc_target.price,
                            )
                        else:
                            target_buy_price = target.price
                            # if iii > 0:
                            #     futbin_price_result = self.get_player_data_from_futbin_with_name(
                            #         player_name=target.player_card.name,
                            #         player_rate=target.player_card.rating,
                            #     )
                            #     if futbin_price_result.get('futbin_price_list'):
                            #         target_buy_price = int(futbin_price_result.get('futbin_price_list')[0]) or target.price
                            buy_result = self.public_moves.console_search_player_and_bid(
                                target.player_card,
                                sbc_price=target_buy_price,
                                max_change_grade=3,
                                wait_for_fix_name=False,
                            )
                        if buy_result.get('result') in ['sid', 'not_bought',
                                                        'player name not found', 'need_check_credit']:
                            new_print(self.fifa_account, 'target not bought , try again , result : ', buy_result)
                            try:
                                # if iii == 0:
                                #     continue
                                if target.sbc_target and target.sbc_target.target_filter:
                                    message_text = f'can`t buy target_1 {target.sbc_target.target_filter}' \
                                                   f' with price {target.sbc_target.target_filter.buy_now_price} , ' \
                                                   f' {self.fifa_account} , {buy_result}'
                                elif target.player_card:
                                    message_text = (f'can`t buy target_2 {target.player_card}'
                                                    f' with price {target_buy_price or target.price}'
                                                    f' {self.fifa_account} , {buy_result}')
                                    if buy_result.get('result') == 'not_bought':
                                        print_cache2.rpush('cant_buy_players', json.dumps(
                                            {'asset_id': target.player_card.asset_id,
                                             'buy_now_price': target_buy_price or target.price,
                                             'create_time': timezone.localtime().isoformat()}
                                        ))
                                else:
                                    message_text = f'can`t buy target_3 {target.sbc_target.player}' \
                                                   f' with price {target.sbc_target.price} , ' \
                                                   f' {self.fifa_account} , {buy_result}'
                                self.send_message(bot, 123, message_text)
                            except:
                                pass
                        else:
                            some_items_bought = True
                            break
                if some_items_bought:
                    new_print(self.fifa_account, 'some items bought , try again')
                    self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                    continue
                else:
                    new_print(self.fifa_account, 'not item bought')
                    break
        self.public_moves.console_close_ultimate(need_get_new_sid=False)
        set_sub_log(self.sbc_worker, 'sbc solver web app handler done')
        new_print(self.fifa_account, 'sbc solver end ...')
        return result

    # def sbc_solver_web_app_handler(self):
    #     set_sub_log(self.sbc_worker, 'sbc solver web app handler start')
    #     new_print(self.fifa_account, 'sbc solver web app handler start ...')
    #     self.public_moves.console_open_ultimate(state_set='home_main', have_to=True)
    #     if self.fifa_account.is_running_console_trade_one or self.fifa_account.run_console_invest_trade_one:
    #         self.invest_move_items_to_club()
    #     AccountSBCNeedPlayer.objects.filter(fifa_account=self.fifa_account).delete()
    #     solver_server_handler = SBCSolverServerSideHandlerWorker.objects.filter(
    #         fifa_account=self.fifa_account, sbc_worker=self.sbc_worker, is_done=False
    #     ).last()
    #     if not solver_server_handler or (
    #             solver_server_handler.create_time < timezone.localtime() - timezone.timedelta(seconds=60 * 15)):
    #         solver_server_handler = SBCSolverServerSideHandlerWorker.objects.create(
    #             fifa_account=self.fifa_account, sbc_worker=self.sbc_worker, status='0')
    #         new_print(self.fifa_account, 'sbc solver server side created . wait for result ...')
    #     else:
    #         new_print(self.fifa_account, 'sbc solver server side exists . wait for result ...')
    #     for nm in range(60 * 60):
    #         solver_server_handler.refresh_from_db()
    #         if solver_server_handler.has_error or solver_server_handler.is_done:
    #             if solver_server_handler.sbc_complete_status == 'all sbc completed':
    #                 if (solver_server_handler.is_done and
    #                         AccountSalablePlayerCard.objects.filter(fifa_account=self.fifa_account)):
    #                     set_sub_log(self.sbc_worker, f'sell items 2 staring ...')
    #                     set_sbc_status(self.sbc_worker, 'selling items 2 ...')
    #                     self.console_transfer_list_sell_items(need_get_new_sid=False)
    #                 break
    #             # print('ok work is done')
    #             # needed_players = AccountSBCNeedPlayer.objects.filter(fifa_account=fifa_account)
    #             for target in AccountSBCNeedPlayer.objects.filter(fifa_account=self.fifa_account):
    #                 for i in range(2):
    #                     buy_result = self.public_moves.console_search_player_and_bid(
    #                         target.sbc_target.player,
    #                         target_filter=target.sbc_target.target_filter,
    #                         sbc_price=target.sbc_target.price,
    #                     )
    #                     if buy_result.get('result') in ['sid', 'not_bought']:
    #                         new_print(self.fifa_account, 'target not bought , try again')
    #                     else:
    #                         break
    #
    #             self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
    #             break
    #         self.public_moves.ps4_buttons.right()
    #         time.sleep(1)
    #         self.public_moves.ps4_buttons.left()
    #         time.sleep(10)
    #     set_sub_log(self.sbc_worker, 'sbc solver web app handler done')
    #     new_print(self.fifa_account, 'sbc solver end ...')

    def squad_battle_core(self):
        self.sbc_worker.refresh_from_db()
        set_sub_log(self.sbc_worker,
                    f'start squad battle for account {self.fifa_account.name_in_console}_{self.fifa_account.platform},'
                    f' played games : {self.fifa_account.account_played_games}')
        try:
            if self.fifa_account.delete_console_reason not in [None, '']:
                new_print(self.fifa_account, 'fifa account delete console : ', self.fifa_account.delete_console_reason)
                time.sleep(1000)
                return
            set_sub_log(self.sbc_worker, 'opening ultimate ...')
            try:
                self.public_moves.console_open_ultimate(state_set='home_main', close_game=True)
            except OSError as screen_grap_error:
                if 'screen grab failed' in str(screen_grap_error):
                    new_print(self.fifa_account, 'screen grap error , ', screen_grap_error, ' restart pc , ',
                              ' full trace : ', traceback.format_exc())
                    self.send_message(
                        bot, 123,
                        f'screen grap error\n account {self.fifa_account}\n console : {self.fifa_account.console}\n restarting...',
                        message_thread_id=ARZBAZI_REPORT_TOPIC_LOGS_THREAD_MESSAGE_ID)
                    set_sbc_status(self.sbc_worker, 'screen grap error , restarting')
                    time.sleep(10)
                    os.system("shutdown /r /t 1")
                else:
                    raise screen_grap_error

            set_sbc_status(self.sbc_worker, f'login to account in console was success')
            # self.public_moves.go_to_state('ps4_main', 'home_main')
            if self.fifa_account.run_force_discharge:
                self.fifa_account.refresh_from_db()
                self.fifa_account.run_force_discharge = False
                self.fifa_account.save(update_fields=['run_force_discharge'])
                self.sbc_worker.refresh_from_db()
                set_sub_log(self.sbc_worker, f'force discharge start ...')
                new_print(self.fifa_account, f'force discharge start ...')
                self.sbc_worker.status = f'force discharge start ...'
                self.sbc_worker.status_change_time = timezone.localtime()
                self.sbc_worker.save(update_fields=['status', 'status_change_time'])
                # self.run_web_app_handler(need_fix_main_squad=0)
                self.squad_battle_handler(need_fix_main_squad=0)
                force_discharge_start_coin_greater = ConsoleBotSetting.objects.get(name='force_discharge_start_coin_greater').int_value

                if ((self.fifa_account.credit > force_discharge_start_coin_greater ) and
                        self.fifa_account.run_discharge and
                        self.sbc_worker.must_done is False and
                        (allowed_discharge_time())
                ):
                    new_print(self.fifa_account, 'need to force discharge. current credit : ', self.fifa_account.credit)
                    try:
                        set_sub_log(self.sbc_worker, f'force discharge start ...')
                        self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                        if self.fifa_account.is_running_console_trade_one or self.fifa_account.run_console_invest_trade_one:
                            self.invest_move_items_to_club()
                        new_print(self.fifa_account, 'sell items before discharge')
                        sell_items(self, self.sbc_worker, self.fifa_account)
                        self.discharge_with_snipe(self.fifa_account.credit, sell_all=True)
                        set_sub_log(self.sbc_worker, f'force discharge end ...')
                    except:
                        new_print(self.fifa_account, 'force discharge exception in discharge with snipe :   ',
                                  traceback.format_exc())
                self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                set_sub_log(self.sbc_worker, f'force discharge end')
                return
            fail_counter = 0
            last_played_games = self.fifa_account.account_played_games

            game_counter = 0
            run_sbc_solving = False
            all_sbc_completed = False
            discharge_started = False
            listing_items_done = False
            worker_played_games = 0
            while game_counter < 15:
                close_old_connections()
                game_counter += 1
                need_fix_main_squad = 0
                discharge_start_coin_greater = ConsoleBotSetting.objects.get(name='discharge_start_coin_greater').int_value
                discharge_start_coin_lower = ConsoleBotSetting.objects.get(name='discharge_start_coin_lower').int_value
                # first_sbc = SBCType.objects.filter(console_can_use=True, must_done=1).order_by('priority').first()
                last_trade_history = ConsoleTradeOneHistory.objects.filter(fifa_account=self.fifa_account).last()
                # need_sbc = SBCType.objects.filter(console_can_use=True, must_done=1).exclude(
                #     id__in=SBCProcess.objects.filter(
                #         worker_id=self.sbc_worker.id, is_done=True
                #     ).distinct('sbc_type').values_list('sbc_type__id', flat=True)
                # )
                uncompleted_sbc_filter = SBCType.objects.filter(console_can_use=True, must_done=1).exclude(
                    id__in=SBCProcess.objects.filter(
                        sbc_number__in=SBCType.objects.filter(
                            console_can_use=True, must_done=1
                        ).values_list('sbc_number', flat=True),
                        worker__fifa_account__id=self.fifa_account.id, is_done=True
                    ).distinct('sbc_type').values_list('sbc_type__id', flat=True)
                )
                # uncompleted_sbc_price = uncompleted_sbc_filter.aggregate(
                #     Sum('sbc_actual_price')).get('sbc_actual_price__sum') or 0
                # if uncompleted_sbc_price > 8000:
                #     uncompleted_sbc_price = 8000
                uncompleted_sbc_price = 0
                uncompleted_sbc = uncompleted_sbc_filter.count()
                completed_sbc = SBCType.objects.filter(
                    console_can_use=True, must_done=1,
                    id__in=SBCProcess.objects.filter(
                        sbc_number__in=SBCType.objects.filter(
                            console_can_use=True, must_done=1
                        ).values_list('sbc_number', flat=True),
                        worker__fifa_account__id=self.fifa_account.id, is_done=True
                    ).distinct('sbc_type').values_list('sbc_type__id', flat=True)
                ).count()
                # if first_sbc in need_sbc:
                #     started_first_sbc = False
                # else:
                #     started_first_sbc = True
                self.fifa_account.refresh_from_db()
                self.sbc_worker.refresh_from_db()
                # console_last_24_hour_played = FifaAccountSquadGame.objects.filter(
                #     fifa_account__in=self.fifa_account.console.fifaaccount_set.filter(
                #         Q(delete_console_reason=None) | Q(delete_console_reason='')
                #     ),
                #     create_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                # )
                account_24_hour_played = int(FifaAccountSquadGame.objects.filter(
                    fifa_account=self.fifa_account,
                    create_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                ).count()) or 0
                # account__31_day_played = int(FifaAccountSquadGame.objects.filter(
                #     fifa_account=self.fifa_account,
                #     create_time__gt=timezone.localtime() - timezone.timedelta(days=31)
                # ).count()) or 0
                account_all_played_games = int(FifaAccountSquadGame.objects.filter(
                    fifa_account=self.fifa_account,
                    # create_time__gt=timezone.localtime() - timezone.timedelta(days=31)
                ).count()) or 0
                account_salable_cards = list(AccountSalablePlayerCard.objects.filter(
                    fifa_account=self.fifa_account))
                current_items, created = FifaAccountCurrentItems.objects.get_or_create(
                    fifa_account=self.fifa_account
                )
                moment_done = FifaAccountMomentsGame.objects.filter(fifa_account=self.fifa_account).count()

                if self.sbc_worker.must_done is False and moment_done == 0:
                    set_main_log(self.sbc_worker, 'doing moment')
                    do_moments_result = self.public_moves.do_moments()
                    if do_moments_result == 'low heal':
                        new_print(self.fifa_account, 'going to buy heal 5')
                        self.public_moves.buy_healing(5)
                        fail_counter += 1
                        if fail_counter < 5:
                            continue
                        need_fix_main_squad = 1
                    if do_moments_result == 'need some things in active squad':
                        set_sub_log(self.sbc_worker, 'need fix main squad')
                        need_fix_main_squad = 1
                    if do_moments_result == 'need_change_manager':
                        set_sub_log(self.sbc_worker, 'need fix main squad')
                        need_fix_main_squad = 2
                    if do_moments_result is False:
                        set_sub_log(self.sbc_worker, 'something is wrong in find scoreboard')
                        new_print(self.fifa_account, '** warning : doing moments , something is wrong **')
                        time.sleep(1 * 60)
                    if do_moments_result is True:
                        need_fix_main_squad = 0
                    time.sleep(10)
                    if need_fix_main_squad:
                        self.public_moves.console_close_ultimate(need_get_new_sid=False)
                        set_sub_log(self.sbc_worker, 'doing moment need fix squad')
                        self.squad_battle_handler(need_fix_main_squad=need_fix_main_squad)
                        # try to do moments again
                        do_moments_result = self.public_moves.do_moments()
                    if do_moments_result is True:
                        self.public_moves.console_close_ultimate(need_get_new_sid=False)
                        set_sub_log(self.sbc_worker, 'doing moment done , sell items')
                        login_result = logout_login(self, self.sbc_worker, self.fifa_account)
                        if login_result.get('status_bool') is False:
                            new_print(self.fifa_account, 'error on login 1 , ', login_result)
                            set_sbc_status(self.sbc_worker, 'login failed')
                            time.sleep(10)
                            raise Exception(login_result.get('reason'))
                        if self.fifa_account.is_running_console_trade_one or self.fifa_account.run_console_invest_trade_one:
                            self.invest_move_items_to_club()
                        new_print(self.fifa_account, 'sell items after list on transfer market 2')
                        try:
                            sell_items(self, self.sbc_worker, self.fifa_account)
                        except:
                            new_print(self.fifa_account, 'exception in list items 2 ', traceback.format_exc())
                        self.console_transfer_list_sell_items(need_get_new_sid=False)
                    else:
                        new_print(self.fifa_account, 'cant complete moments , so set need fix squad')
                        FifaAccountMomentsGame.objects.create(
                            fifa_account=self.fifa_account,
                            moment_number=0,
                            need_fix_squad=True
                        )
                if self.fifa_account.credit == 0 and (self.fifa_account.run_sbc or self.fifa_account.run_discharge):
                    new_print(self.fifa_account, 'credit 0 , start go to app , to create club for other workers')
                    self.public_moves.go_to_state('ps4_main', 'ultimate_team')
                    self.console_close_ultimate(need_get_new_sid=False, state='home_main')
                    login_result = logout_login(self, self.sbc_worker, self.fifa_account)
                    if login_result.get('status_bool') is False:
                        new_print(self.fifa_account, 'error on login 2 , ', login_result)
                        set_sbc_status(self.sbc_worker, 'login failed')
                        time.sleep(10)
                        raise Exception(login_result.get('reason'))
                    self.fifa_account.refresh_from_db()
                    new_print(self.fifa_account, 'credit 0 works end')
                if (
                        self.fifa_account.account_played_games < self.fifa_account.allowed_play_game or
                        self.fifa_account.squad_special_game_one is False or
                        self.fifa_account.squad_special_game_two is False
                ) and (
                        worker_played_games <= 10 and
                        account_24_hour_played <= self.fifa_account.allowed_play_game_day and
                        # account__31_day_played < 88
                        (account_all_played_games < ACCOUNT_ALLOWED_PLAYED_ALL or account_all_played_games > 400 or
                         self.fifa_account.console.name in list(range(90, 100))
                                # self.fifa_account.console.name in [120, 2040, 2041, 2042, 2043, 2044, 2045]
                                # self.fifa_account.fifaaccountsquadgame_set.filter(
                                #     difficulty__in=['semi_pro', 'professional']).count() > 70
                        )
                # ) and (
                #         (console_last_24_hour_played.count() + int(bool(need_sbc and self.fifa_account.run_sbc))) <
                #         self.fifa_account.console.allowed_play_game_day
                ) and (
                        self.fifa_account.run_squad_battle and
                        self.sbc_worker.must_done is False and
                        run_sbc_solving is False
                ) and (
                        calculate_need_game2(
                            # console_last_24_hour_played.count(),
                            account_played=self.fifa_account.account_played_games,
                            # console_limit=self.fifa_account.console.allowed_play_game_day,
                            account_limit_play=self.fifa_account.allowed_play_game,
                            account_play_day=self.fifa_account.fifaaccountsquadgame_set.filter(
                                create_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                            ).count(),
                            account_limit_day=self.fifa_account.allowed_play_game_day
                        ) > 0 or self.fifa_account.squad_special_game_one is False or
                        self.fifa_account.squad_special_game_two is False
                # ) and (
                        # not self.fifa_account.is_running_console_trade_one or
                        # (last_trade_history and last_trade_history.transfer_list_items_count <= 95 and
                        #  last_trade_history.unassigned_item_count <= 0)
                        # (self.fifa_account.stop_console_trade_one_for_other_bots and
                        #  last_trade_history and last_trade_history.transfer_list_items_count <= 20)
                ):
                    try:
                        new_print(self.fifa_account, 'need to run play games')
                        need_games = calculate_need_game2(
                            # console_last_24_hour_played.count(),
                            account_played=self.fifa_account.account_played_games,
                            # console_limit=self.fifa_account.console.allowed_play_game_day,
                            account_limit_play=self.fifa_account.allowed_play_game,
                            account_play_day=self.fifa_account.fifaaccountsquadgame_set.filter(
                                create_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                            ).count(),
                            account_limit_day=self.fifa_account.allowed_play_game_day
                        )
                        result = self.public_moves.play_squad_battle_games(
                            play_games=need_games
                        )
                        if result == 'low heal':
                            new_print(self.fifa_account, 'going to buy heal 5')
                            self.public_moves.buy_healing(5)
                            fail_counter += 1
                            if fail_counter < 5:
                                continue
                            need_fix_main_squad = 1
                        if result == 'need some things in active squad':
                            set_sub_log(self.sbc_worker, 'need fix main squad')
                            need_fix_main_squad = 1
                        if result == 'need_change_manager':
                            set_sub_log(self.sbc_worker, 'need fix main squad')
                            need_fix_main_squad = 2
                        if result is False:
                            set_sub_log(self.sbc_worker, 'something is wrong in find scoreboard')
                            new_print(self.fifa_account, '** warning : something is wrong **')
                            time.sleep(2 * 60)
                            if fail_counter == 2:
                                need_fix_main_squad = 1
                        if result is True:
                            worker_played_games += need_games
                        if result == 'can not find good opponent':
                            worker_played_games += 11
                    except Exception as error2:
                        self.public_moves.ps4_buttons.reset_to_default()
                        self.public_moves.release_buttons_after_game()
                        new_print(self.fifa_account, 'try play game but got exception : ', traceback.format_exc())
                        set_sbc_status(self.sbc_worker, 'unnormal error in play game')
                        # self.sbc_worker.refresh_from_db()
                        # self.sbc_worker.status = 'unnormal error in play game'
                        # self.sbc_worker.status_change_time = timezone.localtime()
                        # self.sbc_worker.save()
                elif (
                        self.fifa_account.run_sbc and
                        self.sbc_worker.must_done is False and
                        uncompleted_sbc > 0 and
                        all_sbc_completed is False and
                        (self.fifa_account.credit > uncompleted_sbc_price
                         # (completed_sbc > 0 and self.fifa_account.credit > 5000)
                        ) and
                        (not self.fifa_account.is_running_console_trade_one or
                         (last_trade_history and last_trade_history.transfer_list_items_count <= 95 and
                         last_trade_history.unassigned_item_count <= 0))
                ):
                    run_sbc_solving = True
                    set_sub_log(self.sbc_worker, 'need to run sbc solver')
                    new_print(self.fifa_account, 'need to run sbc solver')
                    # thread_1 = threading.Thread(target=self.sbc_solver_web_app_handler_2)
                    # thread_1.start()
                    # while thread_1.is_alive():
                    #     new_print(self.fifa_account, 'waiting sbc solver end , pressing left and right')
                    #     self.public_moves.ps4_buttons.right()
                    #     time.sleep(1)
                    #     self.public_moves.ps4_buttons.left()
                    #     time.sleep(100)
                    sbc_solve_result = self.sbc_solver_func()
                    if sbc_solve_result == 'all sbc completed':
                        all_sbc_completed = True
                    elif sbc_solve_result == 'no credit':
                        new_print(self.fifa_account, 'no credit for solve sbc. stop sbc solver.')
                        all_sbc_completed = True
                    elif sbc_solve_result == 'must done':
                        new_print(self.fifa_account, 'bot has some error , stop work sbc again')
                        all_sbc_completed = True
                    game_counter += 1
                    continue
                elif (
                        # todo : remove bellow after ramin conversation
                        self.fifa_account.console.name in list(range(0, 9000)) and
                        #
                        (discharge_start_coin_greater < self.fifa_account.credit < discharge_start_coin_lower) and
                        discharge_started is False and
                        self.fifa_account.run_discharge and
                        self.sbc_worker.must_done is False and
                        allowed_discharge_time() and
                        (MuleAccounts.objects.filter(
                            in_use=False, error=False,
                            investors__in=[self.fifa_account.console.investor],
                            deleted=False,
                        ).annotate(
                            search_count_24_hour=Coalesce(Subquery(
                                FifaAccountSearch.objects.filter(
                                    fifa_account__id=OuterRef('fifa_account__id'),
                                    search_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                                ).values('fifa_account').annotate(
                                    search_counter=Count('id', output_field=IntegerField())
                                ).values('search_counter'), output_field=IntegerField()
                            ), Value(0))
                        ).filter(search_count_24_hour__lt=self.account_high_search_count).order_by(
                            'last_used').count() > 6 or
                         MuleDischargeMode2.objects.filter(
                             Q(in_use=False) | Q(is_api=True), is_active=True
                         ).count() > 0) and
                        (not self.fifa_account.is_running_console_trade_one or
                         (last_trade_history and last_trade_history.transfer_list_items_count <= 95 and
                          last_trade_history.unassigned_item_count <= 0))
                ):
                    new_print(self.fifa_account, 'need to discharge. current credit : ', self.fifa_account.credit)
                    try:
                        discharge_with_snipe_start_coin_greater = ConsoleBotSetting.objects.get(
                            name='discharge_with_snipe_start_coin_greater').int_value
                        set_main_log(self.sbc_worker, f'discharge start ...')
                        self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                        # time.sleep(30)
                        login_result = logout_login(self, self.sbc_worker, self.fifa_account)
                        if login_result.get('status_bool') is False:
                            set_sbc_status(self.sbc_worker, 'login failed')
                            time.sleep(300)
                            close_old_connections()
                            raise Exception(login_result.get('reason'))
                        # if login_status and str(login_status).startswith('Traceback'):
                        #     set_sbc_status(self.sbc_worker, 'login failed')
                        #     time.sleep(30 * 60)
                        #     raise Exception(str('login failed'))
                        # if login_status in ['chromedriver needed', 'chromedriver update needed', 'console login',
                        #                     'problem in login']:
                        #     set_sbc_status(self.sbc_worker, login_status)
                        #     time.sleep(30 * 60)
                        #     raise Exception(str(login_status))
                        if self.fifa_account.is_running_console_trade_one or self.fifa_account.run_console_invest_trade_one:
                            self.invest_move_items_to_club()
                        new_print(self.fifa_account, 'sell items before discharge')
                        sell_items(self, self.sbc_worker, self.fifa_account)

                        not_using_mules = MuleAccounts.objects.filter(
                            in_use=False, error=False,
                            investors__in=[self.fifa_account.console.investor],
                            deleted=False,
                        ).annotate(
                            search_count_24_hour=Coalesce(Subquery(
                                FifaAccountSearch.objects.filter(
                                    fifa_account__id=OuterRef('fifa_account__id'),
                                    search_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                                ).values('fifa_account').annotate(
                                    search_counter=Count('id', output_field=IntegerField())
                                ).values('search_counter'), output_field=IntegerField()
                            ), Value(0))
                        ).filter(search_count_24_hour__lt=self.account_high_search_count).order_by('last_used')
                        discharge_with_mode3_lowest_target_price = ConsoleBotSetting.objects.get(
                            name='discharge_with_mode3_lowest_target_price').int_value
                        discharge_mode2_interval_hours = ConsoleBotSetting.objects.get(
                            name='discharge_mode2_interval_hours').int_value
                        discharge_mode3_interval_hours = ConsoleBotSetting.objects.get(
                            name='discharge_mode3_interval_hours').int_value
                        discharge_with_mode3_mules = not_using_mules.filter(fifa_account__credit__gte=int(discharge_with_mode3_lowest_target_price * .7)).count()

                        not_using_mules = not_using_mules.count()

                        if self.fifa_account.credit > discharge_with_mode3_lowest_target_price and discharge_with_mode3_mules:
                            new_print(self.fifa_account, 'discharge with mode 3 ( pod snipe ) ')
                            successful_transfer = self.discharge_with_mode3(self.fifa_account.credit, coins_to=1000)
                            if successful_transfer.get('status_bool') is True:
                                new_print(self.fifa_account, 'discharge is success , ', successful_transfer)
                                discharge_started = True
                                continue
                        # else:
                        #     new_print(self.fifa_account, 'discharge with snipe')
                        #     self.discharge_with_snipe(self.fifa_account.credit, sell_all=False)
                        if DischargeMode2.objects.filter(
                                fifa_account=self.fifa_account,
                                create_time__gt=timezone.localtime() - timezone.timedelta(hours=discharge_mode2_interval_hours),
                                status__in=['success', 'failed'],
                        ).count() <= 0 and CloseWebAppTransfers.objects.filter(
                                second_account=self.fifa_account, error=False, second_side_done=True,
                                web_app_start_time__gt=timezone.localtime() - timezone.timedelta(hours=discharge_mode3_interval_hours)
                        ).count() <= 0:
                            sbc_file_work_log = SBCFileWorkLog.objects.create(
                                console=self.fifa_account.console,
                                fifa_account=self.fifa_account,
                                work_type='discharge',
                                work_status='start',
                                work_accounts_count=1,
                                start_time=timezone.localtime(),
                            )

                            discharge_started = True
                            discharge_result = self.discharge_with_mode2(self.fifa_account.credit, coins_to=0)
                            # if (discharge_result in ['no card found', 'no deactive mule found'] and not_using_mules > 6
                            self.fifa_account.refresh_from_db()
                            if (not_using_mules > 6
                                    # todo : remove bellow condition after mules fix
                                    and self.fifa_account.credit > discharge_with_snipe_start_coin_greater):
                                self.discharge_with_snipe(self.fifa_account.credit, sell_all=False)

                            sbc_file_work_log.end_time = timezone.localtime()
                            sbc_file_work_log.work_status = 'end'
                            sbc_file_work_log.save(update_fields=['end_time', 'work_status'])
                        # todo : remove credit condition after mules fix
                        elif not_using_mules > 6 and self.fifa_account.credit > discharge_with_snipe_start_coin_greater:
                            sbc_file_work_log = SBCFileWorkLog.objects.create(
                                console=self.fifa_account.console,
                                fifa_account=self.fifa_account,
                                work_type='discharge',
                                work_status='start',
                                work_accounts_count=1,
                                start_time=timezone.localtime(),
                            )

                            discharge_started = True
                            self.discharge_with_snipe(self.fifa_account.credit, sell_all=False)
                            
                            sbc_file_work_log.end_time = timezone.localtime()
                            sbc_file_work_log.work_status = 'end'
                            sbc_file_work_log.save(update_fields=['end_time', 'work_status'])
                        set_main_log(self.sbc_worker, f'discharge end ...')
                        new_print(self.fifa_account, f'discharge end ...')
                        if self.fifa_account.run_sbc is False and account_salable_cards:
                                new_print(self.fifa_account, 'discharge is active but no sbc worker. sell items starting')
                                self.public_moves.go_to_state('ps4_main', 'ultimate_team')  # go home before start list items . list item page and sold items page have same sign
                                set_sub_log(self.sbc_worker, f'sell items staring ...')
                                set_sbc_status(self.sbc_worker, 'selling items ...')
                                self.console_transfer_list_sell_items(need_get_new_sid=False)
                                listing_items_done = True
                        game_counter += 5
                    except Exception as error3:
                        new_print(self.fifa_account, 'exception in discharge with snipe :   ', traceback.format_exc())
                        if (error3.__str__() == 'need sell from web app' or
                                error3.__str__() == 'need to recheck credit from web'):
                            break
                    continue
                else:
                    game_counter = 15
                    set_sub_log(self.sbc_worker, 'all 40 games done')
                    new_print(self.fifa_account, 'all 40 games done , run sbc : ', run_sbc_solving,
                              ' all sbc complete : ', all_sbc_completed,
                              ' sbc status : ', self.fifa_account.run_sbc,
                              ' squad status : ', self.fifa_account.run_squad_battle,
                              ' discharge status : ', self.fifa_account.run_discharge)
                    # todo : increase unlisted items to 80. for start of fifa decreased.
                    if not listing_items_done and (len(account_salable_cards) >= ACCOUNT_TOO_MANY_UNLISTED_ITEMS3 or current_items.transfer_list_items_count >= ACCOUNT_TOO_MANY_UNLISTED_ITEMS3) and (
                            self.fifa_account.run_squad_battle or
                            self.fifa_account.run_discharge or
                            self.fifa_account.run_sbc
                    ):
                        new_print(self.fifa_account, 'need list items : ', len(account_salable_cards),
                                  ' transfer_list_items_count : ', current_items.transfer_list_items_count,
                                  ' too_many_unlisted : ', ACCOUNT_TOO_MANY_UNLISTED_ITEMS3)
                        self.public_moves.console_close_ultimate(need_get_new_sid=False)
                        login_result = logout_login(self, self.sbc_worker, self.fifa_account)
                        if login_result.get('status_bool') is False:
                            set_sbc_status(self.sbc_worker, 'login failed')
                            time.sleep(10)
                            raise Exception(login_result.get('reason'))
                        if self.fifa_account.is_running_console_trade_one or self.fifa_account.run_console_invest_trade_one:
                            self.invest_move_items_to_club()
                        new_print(self.fifa_account, 'sell items after list on transfer market 2')
                        try:
                            sell_items(self, self.sbc_worker, self.fifa_account)
                        except:
                            new_print(self.fifa_account, 'exception in list items ', traceback.format_exc())
                        self.public_moves.go_to_state('ps4_main',
                                                      'ultimate_team')  # go home before start list items . list item page and sold items page have same sign
                        set_sub_log(self.sbc_worker, f'sell items staring ...')
                        set_sbc_status(self.sbc_worker, 'selling items ...')
                        self.console_transfer_list_sell_items(need_get_new_sid=False)
                        listing_items_done = True
                        self.public_moves.console_close_ultimate(need_get_new_sid=False)
                        time.sleep(30)
                        # login_status = logout_login(self, self.sbc_worker, self.fifa_account)
                        # if login_status.get('status_bool') is False:
                        #     set_sbc_status(self.sbc_worker, 'login failed')
                        #     time.sleep(10)
                        #     raise Exception('login failed')
                        # if self.fifa_account.is_running_console_trade_one or self.fifa_account.run_console_invest_trade_one:
                        #     self.invest_move_items_to_club()
                        # new_print(self.fifa_account, 'sell items after list on transfer market 3')
                        # try:
                        #     sell_items(self, self.sbc_worker, self.fifa_account)
                        # except:
                        #     new_print(self.fifa_account, 'exception in list items ', traceback.format_exc())
                self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                self.sbc_worker.refresh_from_db()
                self.sbc_worker.description = ''
                self.sbc_worker.description_editor = None
                self.sbc_worker.status = f'running web app for account {self.fifa_account.name_in_console}_{self.fifa_account.platform}'
                self.sbc_worker.status_change_time = timezone.localtime()
                self.sbc_worker.save()

                if (need_fix_main_squad
                        or
                        FifaAccountRequest.objects.using('logs_pgbouncer').filter(
                            fifa_account=self.fifa_account,
                            link__startswith='https://accounts.ea.com/connect/auth',
                            create_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                        ).count() < 1
                ):
                    new_print(self.fifa_account, 'less than 1 login in 24 hour , so login and fix squad ,'
                                                 ' need fix squad = ', need_fix_main_squad)
                    if self.fifa_account.use_special_squad and not self.fifa_account.special_squad_ready_to_play:
                        if not need_fix_main_squad:
                            need_fix_main_squad = 1
                    # todo : fix run_web_app_handler to don't use server side
                    # self.run_web_app_handler(need_fix_main_squad=need_fix_main_squad)
                    self.squad_battle_handler(need_fix_main_squad=need_fix_main_squad)
                    self.fifa_account.refresh_from_db()
                    self.fifa_account.stop_console_trade_one_for_other_bots = False
                    self.fifa_account.save(update_fields=['stop_console_trade_one_for_other_bots'])

                # elif (last_trade_history and last_trade_history.transfer_list_items_count <= 40):
                #     new_print(self.fifa_account, 'check transfer list for continue trade 2')
                #     self.run_web_app_handler(need_fix_main_squad=0)
                #     self.fifa_account.refresh_from_db()
                #     self.fifa_account.stop_console_trade_one_for_other_bots = False
                #     self.fifa_account.save()
                self.fifa_account.refresh_from_db()
                if last_played_games == self.fifa_account.account_played_games:
                    fail_counter += 1
                else:
                    fail_counter = 0
                    last_played_games = self.fifa_account.account_played_games
                new_print(self.fifa_account, 'fail counter : ', fail_counter)
                if fail_counter > 5:
                    self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                    set_sbc_status(self.sbc_worker, 'account something error')
                    time.sleep(30 * 60)
                    raise Exception('account something error')
            self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
            set_sbc_status(self.sbc_worker, 'Console Bot End')


        except Exception as error:
            new_print(self.fifa_account, 'exception error 23 : ', traceback.format_exc())
            self.public_moves.ps4_buttons.reset_to_default()
            close_old_connections()
            self.sbc_worker.refresh_from_db()
            self.sbc_worker.description = ''
            self.sbc_worker.description_editor = None
            self.sbc_worker.status = str(error)
            self.sbc_worker.status_change_time = timezone.localtime()
            self.sbc_worker.save()
            time.sleep(200)
        return
