import copy
import datetime
import email
import imaplib
import json
import os
import random
import re
import subprocess
import time
import traceback
import urllib
from email.header import decode_header
from email.utils import parsedate_to_datetime
from hashlib import md5
from threading import Thread

import cloudscraper
import cv2

import numpy as np
import pytz
import requests
import telepot
import unidecode
from PIL import ImageGrab
from bs4 import BeautifulSoup
from django.core.cache import caches
from django.db import connection, connections, close_old_connections
from django.db.models import Q
from django.utils import timezone
from django_redis import get_redis_connection
from requests import Session
from django.contrib.auth.models import User as django_user

from accounts.models import FifaAccount, FifaAccountLog, PlayerCard, AccountSalablePlayerCard, \
    ObjectiveSeasonProgressSpecialOption, TelegramMessage, \
    ConsoleSpecialNames, AccountSoldItem, FifaAccountCurrentItems, ConsoleBotSetting, ConsoleLastStatus, Console
from futplus.settings import BASE_DIR, TIME_ZONE
from sbc import FIFA_REPORT_TOKEN, ARZBAZI_REPORT_GROUP_ID, ARZBAZI_REPORT_TOPIC_DISCHARGE_ERROR_THREAD_MESSAGE_ID, \
    U7BUY_REPORT_CHANNEL_ID, ONE_WEEK_SECONDS, ONE_HOUR_SECONDS
from sbc.models import SBCWorker, SBCProcess, SBCProcessTarget, SBCWorkerDetailsLog, SBCType, SBCSolvationModel
from sniper.models import MuleDischargeMode2, DischargeMode2
from squad_battle.models import AccountSquadBattleData
from trade import console_trade_quality_dict
from trade.models import ConsoleTradeOneQuality
from utils import deep_get
from utils.ea_settings import fifa_host, fifa_23_address, pin_event_url, fut_web_number, futbin_address, \
    fifa_23_address_2, fifa_host_2
from utils.realy_public_methods import get_db_time, telegram_send_message_fifa_account

bot = telepot.Bot(FIFA_REPORT_TOKEN)

user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
# u7buy_trade_api = 'https://fbm-api.shopwegame.com/api/trade'
u7buy_trade_api = 'https://api.u7buyut.com/api/trade'
if os.name == 'nt':
    import diskcache
    console_worker_cache = diskcache.Cache(os.path.join(BASE_DIR, '.data/console_worker_info'))
else:
    console_worker_cache = caches['diskcache_alternative']


def delete_sold_items(se: requests.Session, header, server_key=None):
    options_header = {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'en-US,en;q=0.5',
        'Connection': 'keep-alive',
        'Host': fifa_host,
        'Access-Control-Request-Headers': 'content-type,x-ut-sid',
        'Access-Control-Request-Method': 'DELETE',
        'Origin': 'https://www.ea.com',
        'Referer': 'https://www.ea.com/',
        'User-Agent': user_agent
    }
    se.options(
        f'{fifa_23_address}/trade/sold',
        headers=options_header)
    resp = se.delete(f'{fifa_23_address}/trade/sold',
                     headers=header)
    return resp


def sell_items(parent_instance, sbc_worker: SBCWorker, fifa_account: FifaAccount, sell_club_players=False,
               check_transfer_list=True, update_trade_pile=False, check_players_pick=True):
    set_sub_log(sbc_worker, 'sell items, managing items from web')
    from sbc.sbc_solver import SBCSolver
    parent_instance : SBCSolver = parent_instance
    sbc_worker.refresh_from_db()
    # if not parent_instance.can_get_help_for_discharge:
    #     # if sbc_worker.status == 'discharging ...' and \
    #     #         (sbc_worker.status_change_time.astimezone(get_current_timezone()) < timezone.localtime() - timedelta(minutes=65)):
    #     if sbc_worker.status == 'discharging ...':
    #         new_print(fifa_account, 'can_get_help_for_discharge ...')
    #         parent_instance.can_get_help_for_discharge = True
    new_print(fifa_account, 'sell items , sell club players : ', sell_club_players,
              ' check transfer list : ', check_transfer_list,
              ' update_trade_pile : ', update_trade_pile,
              ' check_players_pick : ', check_players_pick)
    if check_players_pick:
        try:
            get_players_pick = parent_instance.se.get(f'{fifa_23_address}/playerpicks/pending')
            save_account_request(fifa_account=fifa_account, link=f'{fifa_23_address}/item/select_misc_2')
            get_players_pick_json = get_players_pick.json()
            if get_players_pick_json.get('availablePicks'):
                sorted_players = sorted(get_players_pick_json['itemData'], key=lambda x: x["rating"], reverse=True)
                data_item_ids = {'itemIds': [sorted_players[0]['resourceId']]}
                resp = parent_instance.se.post(
                    f'{fifa_23_address}/playerpicks/item/select/v2',
                    json=data_item_ids,
                    headers=parent_instance.main_dic['header'])
                save_account_request(
                    fifa_account=fifa_account,
                    link=f'{fifa_23_address}/item/select_misc_v2'
                )
                new_print(fifa_account, 'misc select response : ', resp.text[:1000])
        except:
            new_print(fifa_account, 'exception in get_players_pick : ', traceback.format_exc())


    if check_transfer_list is True:
        trade_pile_resp = get_trade_pile(fifa_account, parent_instance.se, parent_instance.main_dic, parent_instance.server_key)
        try:
            save_sold_items(fifa_account, trade_pile_resp.json())
        except:
            new_print(fifa_account, 'cant save sold items : ', traceback.format_exc())
        delete_sold_items(parent_instance.se, parent_instance.main_dic['header'], parent_instance.server_key)
        save_account_request(
            fifa_account=fifa_account,
            link=f'{fifa_23_address}/trade/sold',
        )
    try:
        fifa_account_current_items, cc = FifaAccountCurrentItems.objects.get_or_create(
                    fifa_account=fifa_account
            )
    except:
        new_print(fifa_account, 'how many current_items exists for one account?? , exception : ',
                  traceback.format_exc())
        fifa_account_current_items, cc = FifaAccountCurrentItems.objects.filter(
            fifa_account=fifa_account
        ).first()
    # dont remove bellow variables. used in string format
    m_s_q_s_club_bronze0_tradable_items = ConsoleBotSetting.objects.get(name='max_saved_quick_sell_in_club_bronze0_tradable_items').int_value
    m_s_q_s_club_bronze1_tradable_items = ConsoleBotSetting.objects.get(name='max_saved_quick_sell_in_club_bronze1_tradable_items').int_value
    m_s_q_s_club_silver0_tradable_items = ConsoleBotSetting.objects.get(name='max_saved_quick_sell_in_club_silver0_tradable_items').int_value
    m_s_q_s_club_silver1_tradable_items = ConsoleBotSetting.objects.get(name='max_saved_quick_sell_in_club_silver1_tradable_items').int_value
    m_s_q_s_club_gold0_tradable_items = ConsoleBotSetting.objects.get(name='max_saved_quick_sell_in_club_gold0_tradable_items').int_value
    m_s_q_s_club_gold1_tradable_items = ConsoleBotSetting.objects.get(name='max_saved_quick_sell_in_club_gold1_tradable_items').int_value
    #
    current_sbc_club_items = []
    current_sbc_process = SBCProcess.objects.filter(worker=sbc_worker, is_done=0).first()
    if current_sbc_process:
        club_items = SBCProcessTarget.objects.filter(sbc_process=current_sbc_process)
        for item in club_items:
            current_sbc_club_items.append(item.club_id)

    items_list = []
    need_sleep = 0
    parent_instance.main_dic['sleep_time'] = 0
    pin_events_creator(
        fifa_account=fifa_account,
        se=parent_instance.se, persona_id=parent_instance.fifa_account.persona_id,
        nucleus_id=parent_instance.fifa_account.nucleus_id, source="Hub - Home",
        sid=parent_instance.sid, counter=parent_instance.get_pin_events_counter())
    quick_sell_ids_list = []
    if check_transfer_list:
        # resp = get_trade_pile(fifa_account, parent_instance.se, parent_instance.main_dic, parent_instance.server_key)
        json_resp = trade_pile_resp.json()
        trades = json_resp['auctionInfo']
        for trade in trades:
            if trade['tradeState'] == 'closed':
                continue
            club_id = trade['itemData']['id']
            asset_id = trade['itemData']['assetId']
            resource_id = trade['itemData'].get('resourceId', 0)
            discard_value = trade['itemData'].get('discardValue') or 0
            last_sale_price_1 = trade['itemData'].get('lastSalePrice') or 0
            rating = trade['itemData'].get('rating') or 0
            rare_flag = int(trade['itemData'].get('rareflag') or 0)
            market_data_min_price = trade['itemData'].get('marketDataMinPrice')
            market_data_max_price = trade['itemData'].get('marketDataMaxPrice')
            if rating > 74:
                card_type_first_name = 'gold'
            elif rating > 64:
                card_type_first_name = 'silver'
            else:
                card_type_first_name = 'bronze'
            card_type_name = card_type_first_name + f'{int(rare_flag >= 1)}'
            # don't need do anything with tradable items when run web trade
            if parent_instance.running_platform in ['console_web', 'console_web_pc']:
                # sometimes untradable items goes to transfer list , so quick sell it if this bug happened
                if trade['itemData'].get('untradeable'):
                    resp3 = parent_instance.se.delete(
                        f'{fifa_23_address}/item/{club_id}',
                        headers=parent_instance.main_dic['header'])
                    save_account_request(
                        fifa_account=fifa_account,
                        link=f'{fifa_23_address}/item/%s',
                    )
                    save_quick_sold_item(fifa_account, item_id=club_id,
                                         discard_value=discard_value)
                    new_print(fifa_account, 'how untradable item goes to transfer list? remove it.',
                              ' item : ', trade, ' quick sell result : ', resp3.text)
                continue
            if (not trade['tradeState']) or trade['tradeState'] == 'expired':
                if trade['itemData']['itemType'] != 'player':
                    if trade['tradeState'] == 'expired' and resource_id not in parent_instance.useful_items.values():
                        resp2 = parent_instance.se.delete(
                            f'{fifa_23_address}/item/{club_id}',
                            headers=parent_instance.main_dic['header'])
                        save_account_request(
                            fifa_account=fifa_account,
                            link=f'{fifa_23_address}/item/%s',
                        )
                        save_quick_sold_item(fifa_account, item_id=club_id,
                                             discard_value=discard_value)
                        new_print(fifa_account, 'expired , quick sell this item', trade,
                                  ' quick sell result 6 : ', resp2.text)
                        # time.sleep(randint(1, 3))
                        time.sleep(1)
                    else:
                        if parent_instance.running_platform not in ['console', 'console_web', 'console_web_pc']:
                            min_price = market_data_min_price
                            max_price = market_data_max_price
                            if not min_price or not max_price:
                                resp = parent_instance.get_price_limit(club_id)
                                js_resp = resp.json()
                                min_price = js_resp[0]['minPrice']
                                max_price = js_resp[0]['maxPrice']

                            new_print(fifa_account, 'sell this item with min and max : ', trade,
                                      ' , min and max : ', min_price, max_price)
                            parent_instance.item_put_for_sale(
                                club_id, '', 0, start_price=min_price, buy_now_price=max_price)
                            #
                            # resp2 = parent_instance.se.delete(
                            #     f'{fifa_23_address/item/{club_id}',
                            #     headers=parent_instance.main_dic['header'])
                            # save_account_request(
                            #     fifa_account=fifa_account,
                            #     link=f'{fifa_23_address/item/%s',
                            # )
                            # new_print(fifa_account, 'quick sell result 5 : ', resp2.text)
                            # # time.sleep(randint(1, 3))
                            time.sleep(1)
                else:
                    # rating = trade['itemData']['rating']
                    if False and rating < 0:
                        new_print(fifa_account, 'bronze and silver expired item , check data : ', trade)
                        # rare_flag = int(trade['itemData']['rareflag'])
                        if rare_flag == 0 and rating < 65:
                            if discard_value < 600 and fifa_account_current_items.club_bronze0_tradable_items < m_s_q_s_club_bronze0_tradable_items:
                                data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
                                move_result = put_item_for_sale(
                                    parent_instance.se, parent_instance.main_dic['header'], data)
                                save_account_request(
                                    fifa_account=fifa_account,
                                    link=f'{fifa_23_address}/item/pile_club',
                                )
                                if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                    new_print(fifa_account, 'low level item need to quick sell but for now send it to club 1',
                                              ' , asset id : ', asset_id,
                                              ' discard value : ', discard_value
                                              )
                                    fifa_account_current_items.club_bronze0_tradable_items += 1
                                    fifa_account_current_items.save()
                                    continue

                            resp2 = parent_instance.se.delete(
                                f'{fifa_23_address}/item/{club_id}',
                                headers=parent_instance.main_dic['header'])
                            save_account_request(
                                fifa_account=fifa_account,
                                link=f'{fifa_23_address}/item/%s',
                            )
                            save_quick_sold_item(fifa_account, item_id=club_id,
                                                 discard_value=discard_value)
                            new_print(fifa_account, 'transfer list low level player card : club id = ',
                                      club_id, 'asset id = ', asset_id, 'rating = ',
                                      rating, ' rare = ', rare_flag, ' will quick sell ',
                                      ' quick sell result : ', resp2.text)
                            time.sleep(1)
                        else:
                            # if rating > 74:
                            #     card_type_first_name = 'gold'
                            # elif rating > 64:
                            #     card_type_first_name = 'silver'
                            # else:
                            #     card_type_first_name = 'bronze'
                            # card_type_name = card_type_first_name + f'{int(rare_flag >= 1)}'
                            last_trade_quality = ConsoleTradeOneQuality.objects.filter(
                                create_time__gt=timezone.localtime() - timezone.timedelta(hours=3),
                                name=card_type_name).last()
                            item_min_price = market_data_min_price or 0
                            item_max_price = market_data_max_price or 0
                            item_bid_price = trade['startingBid']
                            item_buy_price = trade['buyNowPrice']

                            # if item_min_price == item_bid_price and item_max_price == item_buy_price:
                            if item_min_price == item_bid_price:
                                if rare_flag == 1 or rating > 64:
                                    data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
                                    move_result = put_item_for_sale(
                                        parent_instance.se, parent_instance.main_dic['header'], data, 0)
                                    save_account_request(
                                        fifa_account=fifa_account,
                                        link=f'{fifa_23_address}/item/pile_club',
                                    )
                                    if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                        pass
                                    else:
                                        resp2 = parent_instance.se.delete(
                                            f'{fifa_23_address}/item/{club_id}',
                                            headers=parent_instance.main_dic['header'])
                                        save_quick_sold_item(fifa_account, item_id=club_id,
                                                             discard_value=discard_value)
                                        new_print(fifa_account,
                                                  'item expired with min and max and can`t send club , quick sell : ',
                                                  trade, ' , move result : ', move_result,
                                                  ' , sell resp : ', resp2.text)
                                else:
                                    resp2 = parent_instance.se.delete(
                                        f'{fifa_23_address}/item/{club_id}',
                                        headers=parent_instance.main_dic['header'])
                                    save_quick_sold_item(fifa_account, item_id=club_id,
                                                         discard_value=discard_value)
                                    new_print(fifa_account,
                                              'item expired with min and max and not sold , quick sell : ', trade,
                                              ' , sell resp : ', resp2.text)
                            else:
                                if parent_instance.running_platform in ['console', 'console_web', 'console_web_pc']:
                                    items_list.append(trade['itemData'])
                                    # parent_instance.items_sell_get_list(
                                    #     asset_id, club_id, items_list, trade['itemData']['rareflag'],
                                    #     rating, trade['itemData']['teamid'])
                                else:
                                    if last_trade_quality and last_trade_quality.bid_price > 0:
                                        min_price = get_previous_price_grade(last_trade_quality.sell_price)
                                        max_price = last_trade_quality.sell_price
                                    else:
                                        min_price = market_data_min_price
                                        max_price = market_data_max_price
                                        if not min_price or not max_price:
                                            resp = parent_instance.get_price_limit(club_id)
                                            js_resp = resp.json()
                                            min_price = js_resp[0]['minPrice']
                                            max_price = js_resp[0]['maxPrice']
                                    parent_instance.item_put_for_sale(
                                        club_id, '', 0, start_price=min_price, buy_now_price=max_price)
                            need_sleep = 1
                            time.sleep(1)
                    else:
                        if parent_instance.running_platform not in ['console', 'console_web', 'console_web_pc']:
                            trade_copy = trade['itemData'].copy()
                            trade_copy['tradeState'] = 'expired'
                            items_list.append(trade_copy)
                            # parent_instance.items_sell_get_list(
                            #     asset_id, club_id, items_list, trade['itemData']['rareflag'],
                            #     rating, trade['itemData']['teamid'], expired=True,
                            #     last_sale_price=trade['itemData'].get('lastSalePrice', None))
                        else:
                            if trade['tradeState'] == 'expired':
                                time.sleep(0.5)
                                if (fifa_account.console_trade_one_quality and
                                        fifa_account.run_console_trade_one and
                                        card_type_name == fifa_account.console_trade_one_quality and
                                        1000 > last_sale_price_1 > 1):
                                    new_print(fifa_account, 'console trade active and item is bought for ',
                                              last_sale_price_1, ' so dont quick sell')
                                    trade_copy = trade['itemData'].copy()
                                    trade_copy['tradeState'] = 'expired'
                                    items_list.append(trade_copy)
                                    need_sleep = 1
                                    continue
                                min_price = market_data_min_price
                                max_price = market_data_max_price
                                if not min_price or not max_price:
                                    resp = parent_instance.get_price_limit(club_id)
                                    js_resp = resp.json()
                                    new_print(fifa_account, 'item price limits = ', js_resp)
                                    min_price = js_resp[0]['minPrice']
                                if trade['startingBid'] == min_price:
                                    new_print(fifa_account, 'player card start bid == min price',
                                              'start price : ', trade['startingBid'],
                                              'min price :', min_price,
                                              'club id = ', club_id, 'asset id = ', asset_id,
                                              'rating = ', rating, 'will quick sell')
                                    quick_sell_ids_list.append(club_id)
                                    # resp2 = parent_instance.se.delete(
                                    #     f'{fifa_23_address}/item/{club_id}',
                                    #     headers=parent_instance.main_dic['header'])
                                    # save_account_request(
                                    #     fifa_account=fifa_account,
                                    #     link=f'{fifa_23_address}/item/%s',
                                    # )
                                    # save_quick_sold_item(fifa_account, item_id=club_id,
                                    #                      discard_value=discard_value)
                                    # new_print(fifa_account, 'player card start bid == min price',
                                    #           'club id = ', club_id, 'asset id = ', asset_id,
                                    #           'rating = ', rating, 'will quick sell , ',
                                    #           'quick sell result 2 : ', resp2.text)
                                    # # time.sleep(randint(1, 3))
                                    # time.sleep(1)
                                else:
                                    card_info = get_player_data_by_asset_id(player_asset_id=asset_id)
                                    new_print(fifa_account, 'asset id = ', asset_id, 'rate = ', rating,
                                              'card info = ', card_info, ' last sale price = ', last_sale_price_1,
                                              ' discard value = ', discard_value)
                                    try:
                                        player_cache_name = f'futbin_player_{str(resource_id)}'
                                        futbin_data = parent_instance.players_log_cache.get(player_cache_name)
                                        if futbin_data and futbin_data.get('local_time_stamp') > (time.time() - (ONE_HOUR_SECONDS * 12)):
                                            new_print(
                                                fifa_account,
                                                'log 2, this item was selected from futbin less than one hour ago ',
                                                ' , so use old data again : ', futbin_data)
                                            futbin_result = futbin_data
                                        else:
                                            # price, update_time, fp, fnp, fxp = parent_instance.get_player_price_from_futbin_web_app(
                                            futbin_result = parent_instance.get_player_price_from_futbin_web_app(
                                                card_info[0],
                                                rating,
                                                card_info[1],
                                                player_club=trade['itemData']['teamid'],
                                                player_rare=trade['itemData']['rareflag'],
                                                player_f=card_info[2], player_l=card_info[3],
                                                player_asset_id=asset_id
                                            )
                                            if futbin_result.get('update_time_stamp'):
                                                parent_instance.players_log_cache.set(
                                                    player_cache_name, futbin_result, timeout=ONE_WEEK_SECONDS)
                                        price = futbin_result.get('price')
                                        back_steps = int(price)
                                        for i in range(1):
                                            back_steps = get_previous_price_grade(back_steps)
                                        if int(price) != 0 and back_steps <= int(min_price):
                                            resp2 = parent_instance.se.delete(
                                                f'{fifa_23_address}/item/{club_id}',
                                                headers=parent_instance.main_dic['header'])
                                            save_account_request(
                                                fifa_account=fifa_account,
                                                link=f'{fifa_23_address}/item/%s',
                                            )
                                            save_quick_sold_item(fifa_account, item_id=club_id,
                                                                 discard_value=discard_value)
                                            new_print(fifa_account, 'quick sell this item 1 price = ', price,
                                                      ' and min price = ', min_price,
                                                      ' , quick sell result 3 : ', resp2.text)
                                            time.sleep(1)
                                        else:
                                            new_print(
                                                fifa_account,
                                                'will not quick sell this item player price =', price,
                                                ' and min price =', min_price
                                            )
                                            items_list.append(trade['itemData'])
                                    except:
                                        new_print(fifa_account, 'error 1 in sell items : ', traceback.format_exc())
                            else:
                                saved_player_cards = PlayerCard.objects.filter(
                                    asset_id=asset_id, rare=trade['itemData']['rareflag'],
                                    rating=rating)
                                saved_cards = AccountSalablePlayerCard.objects.filter(
                                    fifa_account=fifa_account,
                                    player_card=saved_player_cards.last()
                                ).select_related('player_card').values(
                                    'id', 'player_card', 'buy_now_price',
                                    'player_card__rating', 'player_card__rare')
                                if saved_cards:
                                    new_print(fifa_account, 'this player already in database : ',
                                              saved_cards)
                                    time.sleep(.5)
                                    continue
                                card_info = get_player_data_by_asset_id(player_asset_id=asset_id)
                                if not card_info[0]:
                                    player_data_found = False
                                    text2 = (f'card not found. update player json.'
                                             f' asset id = {str(asset_id)} ,'
                                             f' console = {str(fifa_account.console)} ,'
                                             f' player name = {str(card_info[0])} , '
                                             f' account = {fifa_account}')
                                    parent_instance.send_message(bot, 123, text2)
                                    try:
                                        player_cache_name = f'futbin_player_{str(resource_id)}'
                                        futbin_data = parent_instance.players_log_cache.get(player_cache_name)
                                        if futbin_data and futbin_data.get('local_time_stamp') > (
                                                time.time() - (ONE_HOUR_SECONDS * 12)):
                                            new_print(
                                                fifa_account,
                                                'log 3, this item was selected from futbin less than one hour ago ',
                                                ' , so use old data again : ', futbin_data)
                                            futbin_result = futbin_data
                                        else:
                                            # price, update_time, fp, fnp, fxp = parent_instance.get_player_price_from_futbin_web_app(
                                            futbin_result = parent_instance.get_player_price_from_futbin_web_app(
                                                player_name=card_info[0], player_rate=rating,
                                                player_known_as=card_info[1], player_club=trade['itemData']['teamid'],
                                                player_rare=rare_flag,
                                                player_f=card_info[2], player_l=card_info[3],
                                                player_asset_id=asset_id,
                                            )
                                            if futbin_result.get('update_time_stamp'):
                                                parent_instance.players_log_cache.set(
                                                    player_cache_name, futbin_result, timeout=ONE_WEEK_SECONDS
                                                )
                                        price = futbin_result.get('price')
                                    except:
                                        new_print(fifa_account, 'error 125 ', traceback.format_exc())
                                        price = 0
                                else:
                                    price = 0
                                    player_data_found = True
                                min_price = market_data_min_price or 0
                                back_steps = int(price)
                                for i in range(2):
                                    back_steps = get_previous_price_grade(back_steps)
                                if int(price) != 0 and back_steps <= int(min_price):
                                    try:
                                        resp2 = parent_instance.se.delete(
                                            f'{fifa_23_address}/item/{club_id}',
                                            headers=parent_instance.main_dic['header'])
                                        save_account_request(
                                            fifa_account=fifa_account,
                                            link=f'{fifa_23_address}/item/%s',
                                        )
                                        save_quick_sold_item(fifa_account, item_id=club_id,
                                                             discard_value=discard_value)
                                        new_print(fifa_account, 'quick sell this item 3 price = ', price,
                                                  ' and min price = ', min_price, ' , quick sell resp 4 : ', resp2.text)
                                    except Exception as player_found_error:
                                        new_print(fifa_account, 'error player not found : ', traceback.format_exc())
                                        if player_data_found:
                                            raise player_found_error
                                    time.sleep(1)
                                    continue
                                else:
                                    player_card = PlayerCard.objects.filter(
                                        asset_id=asset_id, rare=trade['itemData']['rareflag'],
                                        rating=rating).last()
                                    if not player_card:
                                        player_card, created = PlayerCard.objects.get_or_create(
                                            asset_id=asset_id, rare=rare_flag,
                                            rating=rating)
                                    if not player_card.resource_id:
                                        player_card.resource_id = resource_id
                                    if not player_card.position:
                                        player_card.position = trade['itemData'].get('preferredPosition')
                                    if not player_card.alternate_positions:
                                        player_card.alternate_positions = ','.join(trade['itemData'].get('possiblePositions') or [])
                                    if not player_card.team:
                                        player_card.team = trade['itemData'].get('teamid')
                                    if not player_card.nation:
                                        player_card.nation = trade['itemData'].get('nation')
                                    player_card.name = card_info[0]
                                    player_card.unicode_name = unidecode.unidecode(card_info[0].lower())
                                    if price:
                                        player_card.price = int(price)
                                        player_card.update_time = timezone.localtime()
                                    player_card.save()
                                    if price:
                                        start_price = get_previous_price_grade(price)
                                        if start_price > 20000:
                                            new_start_price = get_round_price(price * .9)
                                            if new_start_price > min_price:
                                                start_price = new_start_price
                                        buy_now_price = price
                                    else:
                                        start_price = 0
                                        buy_now_price = 0
                                    AccountSalablePlayerCard.objects.create(
                                        fifa_account=fifa_account, player_card=player_card,
                                        buy_start_price=start_price, buy_now_price=buy_now_price
                                    )
                                    new_print(fifa_account,
                                              'player card found in transfer list and will not quick sell : ', trade)
                                    try:
                                        if int(price) > 500000:
                                            text = f'''
                                            Congratulations. Account {fifa_account.user_name} Earned a good player
                                            player_name = {player_card.name}
                                            player_price = {price}
                                            player_asset = {player_card.asset_id}
                                            player_rare_and_rate = {player_card.rare}, {player_card.rating}
                                            '''.replace('  ', '')
                                            text += (f'\nconsole name = {fifa_account.console}'
                                                     if fifa_account.console else '')
                                            parent_instance.send_message(bot, 123, text)
                                    except:
                                        close_old_connections()
                                        new_print(fifa_account, 'error 131 : ', traceback.format_exc())

                        need_sleep = 1

            # elif trade['tradeState'] == 'expired':
            #
            #     items_sell_get_list(asset_id, club_id, items_list,trade['itemData']['rareflag'])
            #     need_sleep = 1

    if quick_sell_ids_list:
        for _ in range(3):
            if not quick_sell_ids_list:
                break
            batch = quick_sell_ids_list[:30]
            remove_multiple_items = parent_instance.se.post(
                f'https://{fifa_host}/ut/delete/game/fc25/item',
                json={'itemId': batch},
                headers=parent_instance.main_dic['header']
            )
            new_print(
                parent_instance.fifa_account,
                'remove multiple duplicate items 4 :',
                remove_multiple_items,
                remove_multiple_items.text
            )
            save_account_request(
                fifa_account=parent_instance.fifa_account,
                link=f'{fifa_23_address}/item/multiple_quick_sell',
            )
            quick_sell_ids_list = quick_sell_ids_list[30:]
    items = parent_instance.get_items()
    json_resp = items.json()
    unass_data = json_resp['itemData']
    if sell_club_players:
        if fifa_account.use_special_squad:
            new_print(fifa_account, 'sell club players without squad')
            tradeable_club_items = parent_instance.get_bronze_club_players(
                filter_bronze=False, tradeable=True,
                players_list=parent_instance.special_squad_players_build
            )
        else:
            new_print(fifa_account, 'sell club players with squad')
            tradeable_club_items = parent_instance.get_bronze_club_players(
                filter_bronze=False, tradeable=True
            )
        sellable_club_items = []
        # todo : fix me , between two trade list all of items
        if fifa_account.console_trade_one_quality and (
                fifa_account.is_running_console_trade_one or fifa_account.run_console_invest_trade_one):
            new_print(fifa_account, 'want sell club players but some of them is for trade')
            quality_data_2 = console_trade_quality_dict[fifa_account.console_trade_one_quality]
            for nnttu in tradeable_club_items:
                club_id = nnttu['id']
                rating = nnttu['rating']
                rare_flag = nnttu['rareflag']
                last_sale_price = nnttu.get('lastSalePrice', 0)
                if not (quality_data_2[0] <= rating <= quality_data_2[1] and
                        rare_flag == quality_data_2[2] and
                        1 < last_sale_price < 1000
                ) and not (
                        fifa_account.run_console_invest_trade_one and
                        1 < last_sale_price < 1000
                ):
                    sellable_club_items.append(nnttu)
            new_print(fifa_account, 'sellable_club_items : ', len(sellable_club_items))
        # dont sell low level items . this items can use in other sbc
        elif parent_instance.running_platform in ['console', 'console_web', 'console_web_pc']:
            for nnttu in tradeable_club_items:
                if (nnttu.get('discardValue') or 0) > 500:
                    sellable_club_items.append(nnttu)
            new_print(fifa_account, 'sellable_club_items 2: ', len(sellable_club_items))
        else:
            sellable_club_items = tradeable_club_items
        unass_data = unass_data + sellable_club_items[:100]
        # new_print(fifa_account, 'want to sell club players : ', tradeable_club_items)
    quick_sell_ids_list = []
    storage_quick_sell_ids_list = []  # move item to storage or quick sell
    for unass in unass_data:
        asset_id = unass['assetId']
        club_id = unass['id']
        resource_id = unass.get('resourceId', 0)
        item_rating = unass.get('rating', 0)
        item_rare_flag = unass.get('rareflag', 0)
        last_sale_price = unass.get('lastSalePrice', 0)
        item_type = unass.get('itemType')
        discard_value2 = unass.get('discardValue')
        market_data_min_price = unass.get('marketDataMinPrice')
        market_data_max_price = unass.get('marketDataMaxPrice')

        if unass.get('untradeable') is False:
            try:
                save_selling_items(
                    fifa_account,
                    item_id=club_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_value2 or 0
                )
            except:
                new_print(fifa_account, 'save selling items error : ', traceback.format_exc())
        if club_id not in current_sbc_club_items:
            if item_type == 'misc':
                data = '{"apply":[]}'
                resp = parent_instance.se.post(
                    f'{fifa_23_address}/item/{club_id}',
                    data=data, headers=parent_instance.main_dic['header'])
                save_account_request(
                    fifa_account=fifa_account,
                    link=f'{fifa_23_address}/item/select_misc'
                )
                try:
                    try:
                        json_resp = resp.json()
                    except:
                        new_print(fifa_account, 'error 109 : ', traceback.format_exc())
                        resp = parent_instance.se.get(
                            f'{fifa_23_address}/playerpicks/pending',
                            data=data, headers=parent_instance.main_dic['header'])
                        json_resp = resp.json()
                        save_account_request(
                            fifa_account=fifa_account,
                            link=f'{fifa_23_address}/item/select_misc_2'
                        )
                    res_id = json_resp['itemData'][0]['resourceId']
                    res_rating = 0
                    players_rating = []
                    for player_pick_item in json_resp['itemData']:
                        players_rating.append(player_pick_item['rating'])
                        if player_pick_item['rating'] > res_rating:
                            res_id = player_pick_item['resourceId']
                            res_rating = player_pick_item['rating']
                    resp = parent_instance.se.post(
                        f'{fifa_23_address}/playerpicks/item/{res_id}/select',
                        headers=parent_instance.main_dic['header'])
                    save_account_request(
                        fifa_account=fifa_account,
                        link=f'{fifa_23_address}/item/select_misc_3'
                    )
                    json_resp = resp.json()
                    club_id = json_resp['id']
                    data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
                    # new_print(fifa_account, 'data =', data)
                    new_print(fifa_account, 'misc item found .send to club',
                              'pick player ', res_rating, ' in ', players_rating,
                              'data = ', data)
                    put_item_for_sale(parent_instance.se, parent_instance.main_dic['header'], data, 0)
                    save_account_request(
                        fifa_account=fifa_account,
                        link=f'{fifa_23_address}/item/pile_club',
                    )
                except:
                    # new_print(fifa_account, 'error 36', traceback.format_exc())
                    new_print(fifa_account, 'misc item.no need to send to club , error 36', traceback.format_exc())

            # elif unass['untradeable'] or unass['itemType'] == 'contract':
            elif unass['untradeable']:
                data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
                new_print(fifa_account, 'data =', data, ' untradable item. send to club , club id : ', club_id,
                          ' asset_id : ', asset_id, ' rating : ', item_rating, ' rare : ', item_rare_flag,
                          ' type ', unass['itemType'])
                resp = put_item_for_sale(parent_instance.se, parent_instance.main_dic['header'], data, 0)
                json_resp = resp.json()
                save_account_request(
                    fifa_account=fifa_account,
                    link=f'{fifa_23_address}/item/pile_club',
                )
                try:
                    reason = json_resp['itemData'][0]['reason']
                    # new_print(fifa_account, 'duplicate item')
                    new_print(fifa_account, 'duplicate item , club id = ', club_id, ' asset id = ',
                              asset_id, ' will quick sell', ' - reason : ', reason)
                    if unass['itemType'] == 'player':
                        new_print(fifa_account, 'item will moved to storage or quick sell', unass)
                        storage_quick_sell_ids_list.append(club_id)
                        continue
                        # data_2 = {'itemData': [{'id': club_id, 'pile': 'storage'}]}
                        # resp_22 = put_item_for_sale(parent_instance.se, parent_instance.main_dic['header'],
                        #                             json.dumps(data_2), 0)
                        # save_account_request(
                        #     fifa_account=fifa_account,
                        #     link=f'{fifa_23_address}/item/pile_storage',
                        # )
                        # if resp_22.status_code == 200 and resp_22.json().get('itemData', [{}])[0].get('success'):
                        #     new_print(fifa_account, 'item moved to storage ', unass)
                        #     continue
                        # else:
                        #     # todo : if storage full , remove one item if lowest rating exists, and try move again.
                        #     new_print(fifa_account, 'storage is full , fix me , resp : ', resp_22.text)
                    quick_sell_ids_list.append(club_id)
                    # parent_instance.se.delete(f'{fifa_23_address}/item/{club_id}',
                    #                           headers=parent_instance.main_dic['header'])
                    # save_account_request(
                    #     fifa_account=fifa_account,
                    #     link=f'{fifa_23_address}/item/%s',
                    # )
                    # save_quick_sold_item(fifa_account, item_id=club_id, discard_value=discard_value2)
                except:
                    pass
                time.sleep(1)
            elif item_type != 'player':
                # new_print(fifa_account, 'none player item founded')
                if item_type in ['contract', 'health']:
                    # if ((not sbc_worker.first_xi) and
                    #     (not sbc_worker.puzzle_master) and
                    #     parent_instance.manual_loyal
                    # ) or parent_instance.running_platform in [
                    #     'console', 'console_web', 'console_web_pc'] or sbc_worker.order_active_squad:
                    if parent_instance.running_platform in [
                        'console', 'console_web', 'console_web_pc'] or sbc_worker.order_active_squad:
                        data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
                        # new_print(fifa_account, 'data =', data)
                        new_print(fifa_account, 'data =', data,
                                  ' contract or heal found and need keep it.item send to club. id : ', club_id)
                        # put_item_for_sale(data)
                        put_item_for_sale(parent_instance.se, parent_instance.main_dic['header'], data, 0)
                        time.sleep(1)
                        save_account_request(
                            fifa_account=fifa_account,
                            link=f'{fifa_23_address}/item/pile_club',
                        )
                    else:
                        new_print(fifa_account, 'contract or heal found , club id = ', club_id, 'will quick sell')
                        quick_sell_ids_list.append(club_id)
                        # parent_instance.se.delete(
                        #     f'{fifa_23_address}/item/{club_id}',
                        #     headers=parent_instance.main_dic['header'])
                        # save_account_request(
                        #     fifa_account=fifa_account,
                        #     link=f'{fifa_23_address}/item/%s',
                        # )
                        # save_quick_sold_item(fifa_account, item_id=club_id, discard_value=discard_value2)
                        # time.sleep(1)

                    continue

                if parent_instance.running_platform in ['console', 'console_web', 'console_web_pc']:
                    # if parent_instance.all_sbc_completed:
                    if resource_id in parent_instance.useful_items.values():
                        # data = '{"itemData":[{"id":%s,"pile":"trade"}]}' % club_id
                        data = {'itemData': [{'id': club_id, 'pile': 'trade'}]}
                        new_print(fifa_account, 'useful item found , item send to transfer list', 'data =', data)
                        # put_item_for_sale(data)
                        put_item_for_sale(parent_instance.se, parent_instance.main_dic['header'], json.dumps(data), 0)
                        time.sleep(1)
                        save_account_request(
                            fifa_account=fifa_account,
                            link=f'{fifa_23_address}/item/pile_trade',
                        )
                    else:
                        new_print(fifa_account, 'none player item , quick sell this item , resource_id : ',
                                  resource_id, ' , quick sell price ', discard_value2, ' will quick sell')
                        quick_sell_ids_list.append(club_id)
                        # parent_instance.se.delete(
                        #     f'{fifa_23_address}/item/{club_id}',
                        #     headers=parent_instance.main_dic['header'])
                        # save_account_request(
                        #     fifa_account=fifa_account,
                        #     link=f'{fifa_23_address}/item/%s',
                        # )
                        # save_quick_sold_item(fifa_account, item_id=club_id, discard_value=discard_value2)

                else:
                    min_price = market_data_min_price
                    max_price = market_data_max_price
                    if not min_price or not max_price:
                        resp = parent_instance.get_price_limit(club_id)
                        js_resp = resp.json()
                        min_price = js_resp[0]['minPrice']
                        max_price = js_resp[0]['maxPrice']
                    parent_instance.item_put_for_sale(club_id, '', 0, start_price=min_price, buy_now_price=max_price)
                    time.sleep(1)
                # data = '{"itemData":[{"id":%s,"pile":"club"}]}' % \
                #        (club_id)
                # print 'need this one for sbc'
                # print 'data =', data
                # print 'item send to club'
                # # put_item_for_sale(data)
                # resp = put_item_for_sale(data)

            else:

                # if unass['rareflag'] < 2:
                rating = unass['rating']
                if False and rating < 0:
                    if int(unass['rareflag']) == 0:
                        data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
                        new_print(fifa_account, 'data =', data,
                                  ' unassign bronze and silver common item. send to club 2 club id: ', club_id,
                                  ' rating : ', item_rating, ' rare : ', item_rare_flag)
                        resp = put_item_for_sale(parent_instance.se, parent_instance.main_dic['header'], data)
                        json_resp = resp.json()
                        save_account_request(
                            fifa_account=fifa_account,
                            link=f'{fifa_23_address}/item/pile_club',
                        )
                        try:
                            reason = json_resp['itemData'][0]['reason']
                            if reason == 'Invalid deck':
                                # invalid deck means item already in this pile and can not move from this pile to it again
                                # example : item is in pile club and request is move to club
                                new_print(fifa_account, 'item already is in club')
                            else:
                                new_print(fifa_account, 'unassign low level duplicate player card : club id = ',
                                          club_id, ' asset id = ', asset_id, ' rating = ', ' reason = ', reason,
                                          rating, ' rare = ', unass['rareflag'], ' will quick sell')
                                quick_sell_ids_list.append(club_id)
                                # parent_instance.se.delete(
                                #     f'{fifa_23_address}/item/{club_id}',
                                #     headers=parent_instance.main_dic['header'])
                                # save_account_request(
                                #     fifa_account=fifa_account,
                                #     link=f'{fifa_23_address}/item/%s',
                                # )
                                # save_quick_sold_item(fifa_account, item_id=club_id, discard_value=discard_value2)
                        except:
                            pass
                        # new_print(fifa_account, 'unassign low level player card : club id = ',
                        #           club_id, ' asset id = ', asset_id, ' rating = ',
                        #           rating, ' rare = ', unass['rareflag'], ' will quick sell')
                        # resp2 = parent_instance.se.delete(
                        #     f'{fifa_23_address/item/{club_id}',
                        #     headers=parent_instance.main_dic['header'])
                        # save_account_request(
                        #     fifa_account=fifa_account,
                        #     link=f'{fifa_23_address/item/%s',
                        # )
                        # new_print(fifa_account, 'quick sell result : ', resp2.text)
                        # time.sleep(randint(1, 3))
                        time.sleep(1)
                    else:
                        # new_print(fifa_account, 'low level player founded')
                        # todo : forosh behine sazi shavad
                        if parent_instance.running_platform in ['console', 'console_web', 'console_web_pc']:
                            # data = '{"itemData":[{"id":%s,"pile":"trade"}]}' % \
                            #        (club_id)
                            # new_print(fifa_account,'data =', data)
                            # new_print(fifa_account,'item send to transfer list')
                            # # put_item_for_sale(data)
                            # parent_instance.put_item_for_sale(data)
                            # new_print(fifa_account, 'quick sell this item')
                            # parent_instance.se.delete(
                            #     f'{fifa_23_address/item/{club_id}',
                            #     headers=parent_instance.main_dic['header'])
                            # continue
                            items_list.append(unass)
                            # parent_instance.items_sell_get_list(
                            #     asset_id, club_id, items_list, unass['rareflag'],
                            #     rating, unass['teamid'])
                            need_sleep = 1
                        else:
                            min_price = market_data_min_price
                            max_price = market_data_max_price
                            if not min_price or not max_price:
                                resp = parent_instance.get_price_limit(club_id)
                                js_resp = resp.json()
                                min_price = js_resp[0]['minPrice']
                                max_price = js_resp[0]['maxPrice']
                            parent_instance.item_put_for_sale(club_id, '', 0, start_price=min_price,
                                                              buy_now_price=max_price)
                        time.sleep(1)
                    # print 'club id = ',club_id, 'asset id = ', asset_id , 'rating = ',rating, 'will quick sell'
                    # parent_instance.se.delete(f'{fifa_23_address/item/%s' % (
                    #      club_id), headers=parent_instance.main_dic['header'])
                else:
                    sell = 1
                    # if not parent_instance.manual_loyal:
                    #     if unass['rareflag'] < 2:
                    #         if not parent_instance.main_dic['first_xi']:
                    #             sell = parent_instance.check_for_use_in_loyal_sbc(
                    #                 asset_id, 1, 20, sell, unass, team=unass['teamid'])
                    #         if not parent_instance.main_dic['puzzle_master']:
                    #             sell = parent_instance.check_for_use_in_loyal_sbc(
                    #                 asset_id, 4, 36, sell, unass, team=unass['teamid'])

                    if sell:
                        items_list.append(unass)
                        # parent_instance.items_sell_get_list(
                        #     asset_id, club_id, items_list, unass['rareflag'], rating,
                        #     unass['teamid'], last_sale_price=unass.get('lastSalePrice', None))
                        need_sleep = 1
                    else:
                        data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
                        new_print(fifa_account, 'need this one for sbc , data = ', data, 'item send to club')
                        # new_print(fifa_account, 'item send to club')
                        # put_item_for_sale(data)
                        resp = put_item_for_sale(parent_instance.se, parent_instance.main_dic['header'], data, 0)
                        json_resp = resp.json()
                        save_account_request(
                            fifa_account=fifa_account,
                            link=f'{fifa_23_address}/item/pile_club',
                        )
                        try:
                            reason = json_resp['itemData'][0]['reason']
                            new_print(fifa_account, 'duplicate item 2, reason : ', reason)
                            items_list.append(unass)
                            # parent_instance.items_sell_get_list(
                            #     asset_id, club_id, items_list, unass['rareflag'], rating, unass['teamid'])
                            need_sleep = 1
                        except:
                            pass
                        time.sleep(1)
        else:
            data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
            # new_print(fifa_account, 'data =', data)
            new_print(fifa_account, 'item in current_sbc_club_items , send to club , data =', data)
            # put_item_for_sale(data)
            resp = put_item_for_sale(parent_instance.se, parent_instance.main_dic['header'], data, 0)
            save_account_request(
                fifa_account=fifa_account,
                link=f'{fifa_23_address}/item/pile_club',
            )
            time.sleep(2)
            # else:
            #     data = '{"itemData":[{"id":%s,"pile":"trade"}]}' % \
            #            (club_id)
            #     print 'data =', data
            #     print 'item send to trade pile'
            #     put_item_for_sale(data)

    if storage_quick_sell_ids_list:
        sales_data_2 = {'itemData': [
            {'id': iee, 'pile': 'storage'} for iee in storage_quick_sell_ids_list
        ]}
        move_to_storage_result = put_item_for_sale(
            parent_instance.se, parent_instance.main_dic['header'], json.dumps(sales_data_2), 0)
        new_print(fifa_account, 'move multiple to storage result ',
                  move_to_storage_result,
                  move_to_storage_result.text)
        save_account_request(
            fifa_account=fifa_account,
            link=f'{fifa_23_address}/item/multiple_pile_storage',
        )
        time.sleep(1)
        for dd_item in move_to_storage_result.json()['itemData']:
            if dd_item.get('reason') == 'Destination Full':
                quick_sell_ids_list.append(dd_item['id'])

    if quick_sell_ids_list:
        remove_multiple_items = parent_instance.se.post(
            f'https://{fifa_host}/ut/delete/game/fc25/item',
            json={'itemId': [ieee for ieee in quick_sell_ids_list][:30]},
            headers=parent_instance.main_dic['header'])
        new_print(parent_instance.fifa_account,
                  'remove multiple duplicate items 2 : ',
                  remove_multiple_items,
                  remove_multiple_items.text)
        save_account_request(
            fifa_account=parent_instance.fifa_account,
            link=f'{fifa_23_address}/item/multiple_quick_sell',
        )
        quick_sell_ids_list = []
    time.sleep(1)
    if need_sleep:
        transfer_list_ids_list = []
        get_trade_pile_json = get_trade_pile(
            fifa_account, parent_instance.se, parent_instance.main_dic, parent_instance.server_key).json()
        auction_info_trades = get_trade_pile_json['auctionInfo']
        if items_list and len(auction_info_trades) > 99:
            manage_transfer_list_full_destination(parent_instance, fifa_account, auction_info=auction_info_trades)
        # new_print(fifa_account, 'sleep for 330 sec ...')
        # print 'item list = ', items_list
        # time.sleep(30)
        # example : items_list => [ asset_id, club_id, items_list, rare, rate, team_id ]
        for item in items_list:
            if parent_instance.running_platform in ['console', 'console_web_pc']:
                discard_value_3 = item.get('discardValue') or 0
                resource_id = item.get('resourceId')
                market_data_min_price = item.get('marketDataMinPrice')
                market_data_max_price = item.get('marketDataMaxPrice')
                if item.get('rating') > 74:
                    card_type_first_name = 'gold'
                elif item.get('rating') > 64:
                    card_type_first_name = 'silver'
                else:
                    card_type_first_name = 'bronze'
                try:
                    saved_player_cards = PlayerCard.objects.filter(
                        asset_id=item.get('assetId'), rare=item.get('rareflag'),
                        rating=item.get('rating'))
                    saved_cards = AccountSalablePlayerCard.objects.filter(
                        fifa_account=fifa_account,
                        player_card=saved_player_cards.first()
                    ).select_related('player_card').values('id', 'player_card', 'buy_now_price')
                    if saved_cards:
                        new_print(fifa_account, 'this player already in database 2 : ',
                                  saved_cards)
                        time.sleep(2)
                    else:
                        card_type_name = card_type_first_name + f'{int(item.get("rareflag") >= 1)}'
                        time.sleep(0.5)
                        # new_print(fifa_account, 'item price limits 2 = ', js_resp)

                        card_info = get_player_data_by_asset_id(player_asset_id=item.get('assetId'))
                        new_print(fifa_account, 'item price limits 2 = '
                                  'asset id = ', item.get('assetId'),
                                  'rate = ', item.get('rating'), 'rare = ', item.get('rareflag'),
                                  'team_id = ', item.get('teamid'), 'card info = ', card_info,
                                  ' card_type_name = ', card_type_name)
                        last_trade_quality = None
                        if card_type_name in ['bronze1', 'silver0', 'silver1', 'gold0']:
                            last_trade_quality = ConsoleTradeOneQuality.objects.filter(
                                create_time__gt=timezone.localtime() - timezone.timedelta(hours=3),
                                name=card_type_name).last()
                        if last_trade_quality:
                            # new_print(fifa_account, 'bronze and silver and gold common found : ', item)
                            # price = 0
                            # if last_trade_quality and last_trade_quality.bid_price > 0:
                            # if last_trade_quality:
                            #     price = last_trade_quality.sell_price
                            price = last_trade_quality.sell_price
                            player_card, created = PlayerCard.objects.get_or_create(
                                asset_id=item.get('assetId'), rare=item.get('rareflag'), rating=item.get('rating'))
                            player_card.name = card_info[0]
                            player_card.unicode_name = unidecode.unidecode(card_info[0].lower())
                            if price:
                                player_card.price = int(price)
                                player_card.update_time = timezone.localtime()
                            player_card.save()
                            if price:
                                start_price = get_previous_price_grade(price)
                                buy_now_price = price
                            else:
                                start_price = 0
                                buy_now_price = 0
                                new_print(fifa_account, 'good price not found , list with min and max : ', item)
                            AccountSalablePlayerCard.objects.create(
                                fifa_account=fifa_account, player_card=player_card,
                                buy_start_price=start_price, buy_now_price=buy_now_price
                            )
                        else:
                            min_price = market_data_min_price
                            max_price = market_data_max_price
                            if not min_price or not max_price:
                                resp = parent_instance.get_price_limit(item.get('id'))
                                js_resp = resp.json()
                                min_price = js_resp[0]['minPrice']
                            player_cache_name = f'futbin_player_{str(resource_id)}'
                            futbin_data = parent_instance.players_log_cache.get(player_cache_name)
                            if futbin_data and futbin_data.get('local_time_stamp') > (time.time() - (ONE_HOUR_SECONDS * 12)):
                                new_print(
                                    fifa_account,
                                    'log 1 , this item was selected from futbin less than one hour ago ',
                                    ' , so use old data again : ', futbin_data)
                                futbin_result = futbin_data
                            else:
                                # price, update_time, fp, fnp, fxp = parent_instance.get_player_price_from_futbin_web_app(
                                futbin_result = parent_instance.get_player_price_from_futbin_web_app(
                                    player_name=card_info[0], player_rate=item.get('rating'),
                                    player_known_as=card_info[1],
                                    player_club=item.get('teamid'), player_rare=item.get('rareflag'),
                                    player_f=card_info[2], player_l=card_info[3],
                                    player_asset_id=item.get('assetId'),
                                )
                                if futbin_result.get('update_time_stamp'):
                                    parent_instance.players_log_cache.set(
                                        player_cache_name, futbin_result, timeout=ONE_WEEK_SECONDS
                                    )
                            price = futbin_result.get('price')
                            try:
                                player_card, created = PlayerCard.objects.get_or_create(
                                    asset_id=item.get('assetId'), rare=item.get('rareflag'), rating=item.get('rating'))
                            except:
                                player_card = PlayerCard.objects.filter(
                                    asset_id=item.get('assetId'), rare=item.get('rareflag'),
                                    rating=item.get('rating')
                                ).last()
                            player_card.name = card_info[0]
                            player_card.unicode_name = unidecode.unidecode(card_info[0].lower())
                            if not player_card.resource_id:
                                player_card.resource_id = resource_id
                            if price:
                                player_card.price = int(price)
                                player_card.update_time = timezone.localtime()
                            player_card.save()
                            back_steps = int(price)
                            for i in range(1):
                                back_steps = get_previous_price_grade(back_steps)
                            if int(price) != 0 and back_steps <= int(min_price):
                                # new_print(fifa_account, 'quick sell this item price =', price, ' and min price = ', min_price)
                                fifa_account_field_items = getattr(fifa_account_current_items, f'club_{card_type_name}_tradable_items')
                                if discard_value_3 < 600 and fifa_account_field_items < eval(f'm_s_q_s_club_{card_type_name}_tradable_items'):
                                    data = '{"itemData":[{"id":%s,"pile":"club"}]}' % item.get('id')
                                    move_result = put_item_for_sale(
                                        parent_instance.se, parent_instance.main_dic['header'], data)
                                    save_account_request(
                                        fifa_account=fifa_account,
                                        link=f'{fifa_23_address}/item/pile_club',
                                    )
                                    if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                        new_print(fifa_account,
                                                  'low level item need to quick sell but for now send it to club 2',
                                                  ' , asset id : ', item.get('assetId'),
                                                  ' discard value : ', discard_value_3)
                                        setattr(fifa_account_current_items, f'm_s_q_s_club_{card_type_name}_tradable_items', fifa_account_field_items+1)
                                        fifa_account_current_items.save()
                                        continue

                                # resp2 = parent_instance.se.delete(
                                #     f'{fifa_23_address}/item/{item.get("id")}',
                                #     headers=parent_instance.main_dic['header'])
                                # save_account_request(
                                #     fifa_account=fifa_account,
                                #     link=f'{fifa_23_address}/item/%s',
                                # )
                                # save_quick_sold_item(fifa_account, item_id=item.get('id'))
                                new_print(fifa_account, 'quick sell this item 4 price =', price, ' and min price = ',
                                          min_price, ' will quick sell',
                                          # 'resp text : ', resp2.text
                                          )
                                quick_sell_ids_list.append(item.get("id"))
                                # time.sleep(1)
                                continue
                            else:
                                if price:
                                    start_price = get_previous_price_grade(price)
                                    if start_price > 20000:
                                        new_start_price = get_round_price(price * .9)
                                        if new_start_price > min_price:
                                            start_price = new_start_price
                                    buy_now_price = price
                                else:
                                    start_price = 0
                                    buy_now_price = 0
                                AccountSalablePlayerCard.objects.create(
                                    fifa_account=fifa_account, player_card=player_card,
                                    buy_start_price=start_price, buy_now_price=buy_now_price
                                )
                                new_print(fifa_account,
                                          'will not quick sell this item player price=', price, ' and min price= ',
                                          min_price, ' buy now price = ', buy_now_price)
                                try:
                                    if int(price) > 500000:
                                        text = f'''Congratulations. Account {fifa_account.user_name} Earned a good player
                                                    player_name = {player_card.name}
                                                    player_price = {price}
                                                    player_asset = {player_card.asset_id}
                                                    player_rare_and_rate = {player_card.rare}, {player_card.rating}
                                                    sell_items_2, {item.get('lastSalePrice')}
                                                    '''.replace('  ', '')
                                        text += f'\nconsole name = {fifa_account.console}' if fifa_account.console else ''
                                        parent_instance.send_message(bot, 123, text)
                                except:
                                    new_print(fifa_account, 'error 59 : ', traceback.format_exc())
                                    close_old_connections()
                except:
                    new_print(fifa_account, 'error 35', traceback.format_exc())
                new_print(fifa_account, 'item will move to transfer list , ', item)
                transfer_list_ids_list.append(item.get('id'))
                # data = '{"itemData":[{"id":%s,"pile":"trade"}]}' % item.get('id')
                # new_print(fifa_account, 'data =', data, 'item send to transfer list')
                # # new_print(fifa_account, 'item send to transfer list')
                # # put_item_for_sale(data)
                # put_item_for_sale(parent_instance.se, parent_instance.main_dic['header'], data, 0)
                # save_account_request(
                #     fifa_account=fifa_account,
                #     link=f'{fifa_23_address}/item/pile_trade',
                # )
                time.sleep(2)
            elif parent_instance.running_platform in ['console_web', 'console_web_pc']:
                pass
            else:
                parent_instance.sell_process(
                    item.get('assetId'), item.get('id'), '', item.get('rareflag'),
                    item.get('rating'), item.get('teamid'),
                    (item.get('tradeState') == 'expired'))
                time.sleep(3)
        for _ in range(3):
            if not transfer_list_ids_list:
                break
            items_data = {'itemData': [{'id': iie, 'pile': 'trade'} for iie in transfer_list_ids_list[:30]]}
            multiple_put_sale_result = put_item_for_sale(
                parent_instance.se, parent_instance.main_dic['header'], json.dumps(items_data), 0
            )
            new_print(
                parent_instance.fifa_account,
                'put sale multiple items:',
                multiple_put_sale_result,
                multiple_put_sale_result.text
            )
            save_account_request(
                fifa_account=parent_instance.fifa_account,
                link=f'{fifa_23_address}/item/multiple_pile_trade',
            )
            transfer_list_ids_list = transfer_list_ids_list[30:]
    if quick_sell_ids_list:
        for _ in range(3):
            if not quick_sell_ids_list:
                break
            batch = quick_sell_ids_list[:30]
            remove_multiple_items = parent_instance.se.post(
                f'https://{fifa_host}/ut/delete/game/fc25/item',
                json={'itemId': batch},
                headers=parent_instance.main_dic['header']
            )
            new_print(
                parent_instance.fifa_account,
                'remove multiple duplicate items 3 : ',
                remove_multiple_items,
                remove_multiple_items.text
            )
            save_account_request(
                fifa_account=parent_instance.fifa_account,
                link=f'{fifa_23_address}/item/multiple_quick_sell',
            )
            quick_sell_ids_list = quick_sell_ids_list[30:]
    try:
        parent_instance.save_account_items()
    except:
        new_print(fifa_account, 'exception error 133 : ', traceback.format_exc())
        close_old_connections()
    if update_trade_pile:
        get_trade_pile_json_1 = get_trade_pile(
            fifa_account, parent_instance.se, parent_instance.main_dic, parent_instance.server_key).json()
        parent_instance.update_credit(get_trade_pile_json_1.get('credits') or 0)
    else:
        # parent_instance.update_credit()
        if check_transfer_list:
            get_trade_pile_json_1 = trade_pile_resp.json()
            parent_instance.update_credit(get_trade_pile_json_1.get('credits') or 0)
        else:
            get_trade_pile_json_1 = {'auctionInfo': []}
    new_print(fifa_account, 'end of sell items')
    return {'status_bool': True, 'status': 'success', 'trade_pile_auction': get_trade_pile_json_1.get('auctionInfo')}


def manage_transfer_list_full_destination(parent_instance, fifa_account: FifaAccount, auction_info=None):
    from sbc.sbc_solver import SBCSolver
    parent_instance : SBCSolver = parent_instance
    new_print(fifa_account, 'manage_transfer_list_full_destination')
    if auction_info is None:
        get_trade_pile_json = get_trade_pile(fifa_account, parent_instance.se, parent_instance.main_dic,
                                             parent_instance.server_key).json()
        auction_info = get_trade_pile_json['auctionInfo']
    success_counter = 0
    sorted_auction_info = sorted(auction_info, key=lambda d: d['itemData']['rating'])
    for trade_item in sorted_auction_info:
        club_id = trade_item['itemData']['id']
        data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
        move_result = put_item_for_sale(
            parent_instance.se, parent_instance.main_dic['header'], data, 0)
        save_account_request(
            fifa_account=fifa_account,
            link=f'{fifa_23_address}/item/pile_club',
        )
        if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
            success_counter += 1
        if success_counter > 10:
            break


def put_item_for_sale(se, header, data, server_key=None):
    options_header = {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'en-US,en;q=0.5',
        'Connection': 'keep-alive',
        'Host': fifa_host,
        'Access-Control-Request-Headers': 'content-type,x-ut-sid',
        'Access-Control-Request-Method': 'PUT',
        'Origin': 'https://www.ea.com',
        'Referer': 'https://www.ea.com/',
        'User-Agent': user_agent
    }
    se.options(
        f'{fifa_23_address}/item',
        headers=options_header)
    resp = se.put(f'{fifa_23_address}/item', data=data,
                  headers=header)
    return resp


def put_consumable_for_sale(se, header, data):
    options_header = {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'en-US,en;q=0.5',
        'Connection': 'keep-alive',
        'Host': fifa_host,
        'Access-Control-Request-Headers': 'content-type,x-ut-sid',
        'Access-Control-Request-Method': 'PUT',
        'Origin': 'https://www.ea.com',
        'Referer': 'https://www.ea.com/',
        'User-Agent': user_agent
    }
    se.options(
        f'{fifa_23_address}/item/resource',
        headers=options_header)
    resp = se.put(f'{fifa_23_address}/item/resource', data=data,
                  headers=header)
    return resp


def get_squad_battle_data(fifa_account: FifaAccount, se: requests.Session, headers: dict):
    resp = se.get(f'{fifa_23_address}/sqbt/user/hub', headers=headers)
    save_account_request(
        fifa_account=fifa_account,
        link=f'{fifa_23_address}/sqbt/user/hub',
    )
    return resp


def update_account_squad_battle_data(fifa_account: FifaAccount, se: requests.Session, headers):
    resp = get_squad_battle_data(fifa_account=fifa_account, se=se, headers=headers)
    json_resp = resp.json()
    # new_print(fifa_account, 'squad battle data : ', json_resp)
    event_id = json_resp.get('sqbtEventId', 0)
    score = json_resp.get('score', 0)
    user_tier_level = json_resp.get('userTierLevel', 0)
    game_played = json_resp.get('gamesPlayed', 0)
    sqbt_data, created = AccountSquadBattleData.objects.get_or_create(
        fifa_account=fifa_account, event_id=event_id
    )
    sqbt_data.score = score
    sqbt_data.user_tier_level = user_tier_level
    sqbt_data.games_played = game_played
    sqbt_data.save()
    return


def get_trade_pile(fifa_account: FifaAccount, se: requests.Session, main_dic: dict, server_key=None):
    se.options(
        f'{fifa_23_address}/tradepile',
        headers=main_dic['options_header'])
    resp = force_get(
        f'{fifa_23_address}/tradepile',
        fifa_account=fifa_account,
        se=se,
        headers=main_dic['header'])
    save_account_request(
        fifa_account=fifa_account,
        link=f'{fifa_23_address}/tradepile',
    )
    return resp


def get_storage_pile(fifa_account: FifaAccount, se: requests.Session, header: dict):
    resp = force_get(
        f'{fifa_23_address}/storagepile?skuMode=FUT',
        fifa_account=fifa_account,
        se=se,
        headers=header
    )
    save_account_request(
        fifa_account=fifa_account,
        link=f'{fifa_23_address}/storagepile',
    )
    return resp


def get_trade_pile_2(fifa_account: FifaAccount, se: requests.Session, options_header: dict, header: dict):
    if options_header:
        se.options(
            f'{fifa_23_address}/tradepile',
            headers=options_header)
    resp = force_get(
        f'{fifa_23_address}/tradepile',
        fifa_account=fifa_account,
        se=se,
        headers=header)
    save_account_request(
        fifa_account=fifa_account,
        link=f'{fifa_23_address}/tradepile',
    )
    return resp


def get_watchlist(fifa_account: FifaAccount, se: requests.Session, options_header: dict, header: dict):
    se.options(
        f'{fifa_23_address}/watchlist',
        headers=options_header)
    resp = force_get(
        f'{fifa_23_address}/watchlist',
        fifa_account=fifa_account,
        se=se,
        headers=header)
    return resp


def force_get(link, fifa_account: FifaAccount, se=requests.session(), headers=None, save_log=True):
    if headers is None:
        headers = {}
    if save_log is True:
        new_print(fifa_account, 'force get link : ', link)
    while True:
        try:
            return se.get(link, headers=headers)
        except:
            # new_print(fifa_account, traceback.format_exc())
            new_print(fifa_account, 'force get error : ', traceback.format_exc())


def force_post(link, data, fifa_account: FifaAccount, se=requests.session(), headers=None):
    if headers is None:
        headers = {}
    new_print(fifa_account, link, data)
    while True:
        try:
            return se.post(link, data, headers=headers)
        except:
            # new_print(fifa_account, traceback.format_exc())
            new_print(fifa_account, 'force post error : ', traceback.format_exc())


# print_cache = caches['print_log']
print_cache2 = get_redis_connection('print_log')
def new_print(fifa_account: FifaAccount, *args, **kwargs):
    bulk_list = kwargs.get('bulk_list', [])
    if bulk_list and (isinstance(bulk_list, tuple) or isinstance(bulk_list, list)):
        objs = []
        for item in bulk_list:
            text = ''
            if isinstance(item, list) or isinstance(item, tuple):
                for i in item:
                    text += str(i) + ' '
            else:
                text += str(item) + ' '
            objs.append(FifaAccountLog(fifa_account_id=fifa_account.id, description=text))
        FifaAccountLog.objects.using('logs_pgbouncer').bulk_create(objs=objs)

    else:
        text = ''
        for i in args:
            text += str(i) + ' '
        for key, value in kwargs.items():
            text += str(key) + ' : ' + str(value) + ' '
        # print_cache.set(
        #     f'print_log_{fifa_account.id}_{time.time()}',
        #     {'fifa_account_id': fifa_account.id, 'description': text, 'log_time': timezone.localtime()})
        # FifaAccountLog.objects.using('logs').create(fifa_account_id=fifa_account.id, description=text)
        try:
            print_cache2.rpush('print_log2', json.dumps(
                {'fifa_account_id': fifa_account.id, 'description': text, 'log_time': timezone.localtime().isoformat()}
            ))
        except Exception as save_error:
            print('cant save logs : ', json.dumps(
                {'fifa_account_id': fifa_account.id, 'description': text, 'log_time': timezone.localtime().isoformat()}
            ), ' error : ', save_error)
            # print_cache2.rpush('print_log2', json.dumps(
            #     {'fifa_account_id': fifa_account.id, 'description': text, 'log_time': timezone.localtime().isoformat()}
            # ))


def set_sub_log(sbc_worker: SBCWorker, title):
    close_old_connections()
    last_sub = SBCWorkerDetailsLog.objects.filter(worker=sbc_worker, main_job=False).order_by('id').last()
    if last_sub:
        last_sub.end_time = timezone.localtime()
        last_sub.save()
    SBCWorkerDetailsLog.objects.create(worker=sbc_worker, title=title, main_job=False)


def set_main_log(sbc_worker: SBCWorker, title):
    close_old_connections()
    last_sub = SBCWorkerDetailsLog.objects.filter(worker=sbc_worker, main_job=False).order_by('id').last()
    if last_sub:
        last_sub.end_time = timezone.localtime()
        last_sub.save()
    last_main = SBCWorkerDetailsLog.objects.filter(worker=sbc_worker, main_job=True).order_by('id').last()
    if last_main:
        last_main.end_time = timezone.localtime()
        last_main.save()
    SBCWorkerDetailsLog.objects.create(worker=sbc_worker, title=title, main_job=True)


def set_sbc_status(sbc_worker: SBCWorker, status, update_time=True):
    close_old_connections()
    sbc_worker.refresh_from_db()
    update_fields = []
    if status:
        sbc_worker.status = status
        update_fields.append('status')
    if update_time:
        sbc_worker.status_change_time = timezone.localtime()
        update_fields.append('status_change_time')
    sbc_worker.save(update_fields=update_fields)
    try:
        if update_time:
            # todo : remove bellow open file and replace with bellow cache
            with open(os.path.join(BASE_DIR, 'status_update_time.txt'), 'w') as status_time_file:
                status_time_file.write(str(time.time()))
            console_worker_cache.set('status_update_time', str(time.time())) # cache data in local
    except:
        new_print(sbc_worker.fifa_account, 'cant write in status update time , ', traceback.format_exc())
    try:
        if sbc_worker.fifa_account.console:
            console_last_status, created = ConsoleLastStatus.objects.get_or_create(console=sbc_worker.fifa_account.console)
            console_last_status.fifa_account = sbc_worker.fifa_account
            console_last_status.sbc_worker = sbc_worker
            update_fields.append('fifa_account')
            update_fields.append('sbc_worker')
            if status:
                console_last_status.status = status
            if update_time:
                console_last_status.status_change_time = timezone.localtime()
            console_last_status.save(update_fields=update_fields)
        else:
            new_print(sbc_worker.fifa_account, 'no console found to set status , ')
    except:
        print('cant set status')


def set_console_status(console: Console, status, update_time=True):
    try:
        update_fields = []
        console_last_status, created = ConsoleLastStatus.objects.get_or_create(console=console)
        if status:
            console_last_status.status = status
            update_fields.append('status')
        if update_time:
            console_last_status.status_change_time = timezone.localtime()
            update_fields.append('status_change_time')
        console_last_status.save(update_fields=update_fields)
    except:
        print('cant set status 2')


def set_console_list_status(console_name_list: list, status, update_time=True):
    try:
        update_fields = {}
        console_last_status = ConsoleLastStatus.objects.filter(console__name__in=console_name_list)
        if status:
            update_fields['status'] = status
        if update_time:
            update_fields['status_change_time'] = timezone.localtime()
        if update_fields:
            console_last_status.update(**update_fields)
    except:
        print('cant set status 3')


def save_account_request(fifa_account: FifaAccount, link: str, create_time=None):
    if not create_time:
        # print_cache.set(
        #     f'request_log_{fifa_account.id}_{time.time()}',
        #     {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': timezone.localtime()})
        # FifaAccountRequest.objects.using('logs').create(
        #     fifa_account=fifa_account,
        #     link=link,
        # )
        # print_cache2.rpush('request_log2', json.dumps(
        #     {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': timezone.localtime().isoformat()}
        # ))
        save_time = timezone.localtime().isoformat()
    else:
        # print_cache.set(
        #     f'request_log_{fifa_account.id}_{time.time()}',
        #     {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': create_time})
        # FifaAccountRequest.objects.using('logs').create(
        #     fifa_account=fifa_account,
        #     link=link,
        #     create_time=create_time,
        # )
        # print_cache2.rpush('request_log2', json.dumps(
        #     {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': create_time.isoformat()}
        # ))
        save_time = create_time.isoformat()
    try:
        print_cache2.rpush('request_log2', json.dumps(
            {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': save_time}
        ))
    except:
        print('cant save requests : ', json.dumps(
            {'fifa_account_id': fifa_account.id, 'link': link, 'create_time': save_time}
        ))


def process_exists(process_name):
    # query = f'''
    # tasklist /fi "ImageName eq {process_name}" /fo csv 2>NUL | find /I "{process_name}">NUL
    # if "%ERRORLEVEL%"=="0" echo Program is running
    # '''
    # result = os.spawnl(os.P_DETACH, query)
    # if result:
    #     return False
    # else:
    #     return True
    call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name, '/FI', "USERNAME eq %username%"
    # use buildin check_output right away
    output = subprocess.check_output(call, shell=True).decode()
    # check in last line for process name
    last_line = output.strip().split('\r\n')[-1]
    # because Fail message could be translated
    return last_line.lower().startswith(process_name.lower())


xboxs_keyboard = {
    '1': [0, 0, 0], '2': [0, 1, 0], '3': [0, 2, 0], '4': [0, 3, 0], '5': [0, 4, 0], '6': [0, 5, 0],
    '7': [0, 6, 0], '8': [0, 7, 0], '9': [0, 8, 0], '0': [0, 9, 0],

    'q': [1, 0, 0], 'w': [1, 1, 0], 'e': [1, 2, 0], 'r': [1, 3, 0], 't': [1, 4, 0], 'y': [1, 5, 0],
    'u': [1, 6, 0], 'i': [1, 7, 0], 'o': [1, 8, 0], 'p': [1, 9, 0],

    'a': [2, 0, 0], 's': [2, 1, 0], 'd': [2, 2, 0], 'f': [2, 3, 0], 'g': [2, 4, 0], 'h': [2, 5, 0],
    'j': [2, 6, 0], 'k': [2, 7, 0], 'l': [2, 8, 0], "'": [2, 9, 0],

    'z': [3, 0, 0], 'x': [3, 1, 0], 'c': [3, 2, 0], 'v': [3, 3, 0], 'b': [3, 4, 0], 'n': [3, 5, 0],
    'm': [3, 6, 0], ',': [3, 7, 0], '.': [3, 8, 0], '?': [3, 9, 0],

    '!': [0, 0, 1], '@': [0, 1, 1], '#': [0, 2, 1], '$': [0, 3, 1], '%': [0, 4, 1], '&': [0, 5, 1],
    '(': [0, 6, 1], ')': [0, 7, 1], '-': [0, 8, 1], '_': [0, 9, 1],

    '=': [1, 0, 1], '+': [1, 1, 1], '\\': [1, 2, 1], ';': [1, 3, 1], ':': [1, 4, 1], '"': [1, 5, 1],
    '*': [1, 6, 1], '/': [1, 7, 1],

    '<': [2, 4, 1], '>': [2, 5, 1], '[': [2, 6, 1], ']': [2, 7, 1],

    '|': [3, 0, 1], '~': [3, 4, 1], '^': [3, 5, 1],
}

double_check_keyboard = {
    '1': [0, 0, 0], '2': [0, 1, 0], '3': [0, 2, 0], '*': [0, 3, 0],
    '4': [1, 0, 0], '5': [1, 1, 0], '6': [1, 2, 0], '#': [1, 3, 0],
    '7': [2, 0, 0], '8': [2, 1, 0], '9': [2, 2, 0], '-': [2, 3, 0],
    '0': [3, 0, 0],
}


def get_screen_shot(image_name='screen_shot_tmp.jpg'):
    snapshot = ImageGrab.grab()
    save_path = image_name
    snapshot.save(save_path)


def has_image(small_image_name, large_image_name, threshold=.9):
    small_image = cv2.imread(small_image_name)
    large_image = cv2.imread(large_image_name)
    small_image = cv2.cvtColor(small_image, cv2.COLOR_BGR2GRAY)
    large_image = cv2.cvtColor(large_image, cv2.COLOR_BGR2GRAY)
    w, h = large_image.shape[::-1]
    res = cv2.matchTemplate(small_image, large_image, cv2.TM_CCOEFF_NORMED)
    loc = np.where(res >= threshold)
    try:
        assert loc[0][0] > 0
        assert loc[1][0] > 0
        if loc[1][0] >= 0 and loc[0][0] >= 0:
            return True
    except:
        return False


def get_current_active_character(platform):
    keyboards_path = os.path.join(BASE_DIR, f'utils/{platform}_keyboards/')
    keyboard_characters = os.listdir(keyboards_path)
    get_screen_shot()
    for active_character in keyboard_characters:
        if has_image(os.path.join(keyboards_path, active_character), 'screen_shot_tmp.jpg'):
            return active_character[0]


def enter_world_xboxs(parent_instance, english_text, initial_character='y', initial_upper=False, has_emoji=False):
    if initial_upper is True:
        parent_instance.ps4_buttons.l3()
    current_character = xboxs_keyboard.get(get_current_active_character('xboxs') or initial_character)
    count = 0
    for character in english_text:
        count += 1
        if character == ' ':
            parent_instance.ps4_buttons.triangle()
            continue
        select_character = xboxs_keyboard.get(character.lower())
        result_num = select_character[1] - current_character[1]
        if current_character[0] < select_character[0]:
            [parent_instance.ps4_buttons.down() for i in range(select_character[0] - current_character[0])]
        else:
            [parent_instance.ps4_buttons.up() for i in range(current_character[0] - select_character[0])]
        if result_num > 0:
            for i in range(result_num):
                parent_instance.ps4_buttons.right()
        elif result_num < 0:
            for i in range(abs(result_num)):
                parent_instance.ps4_buttons.left()
        if character.isupper():
            parent_instance.ps4_buttons.l3()
        if select_character[2] == 1:
            parent_instance.ps4_buttons.l2()
        parent_instance.ps4_buttons.cross()
        if select_character[2] == 1:
            parent_instance.ps4_buttons.l2()
            if has_emoji:
                time.sleep(.5)
                parent_instance.ps4_buttons.l2()
        current_character = xboxs_keyboard.get(character.lower())


def enter_double_check_code_xbox(parent_instance, english_text, initial_character='6', initial_upper=False):
    # if initial_upper is True:
    #     parent_instance.ps4_buttons.l3()
    current_character = double_check_keyboard.get(initial_character)
    count = 0
    for character in english_text:
        count += 1
        if character == ' ':
            parent_instance.ps4_buttons.triangle()
            continue
        if character == '0':
            [parent_instance.ps4_buttons.down(sleep_after=1) for i in range(3)]
            parent_instance.ps4_buttons.cross()
            current_character = [3, current_character[1], 0]
            continue
        select_character = double_check_keyboard.get(character.lower())
        result_num = select_character[1] - current_character[1]
        if current_character[0] < select_character[0]:
            [parent_instance.ps4_buttons.down(sleep_after=.5) for i in
             range(select_character[0] - current_character[0])]
        else:
            [parent_instance.ps4_buttons.up(sleep_after=.5) for i in range(current_character[0] - select_character[0])]
        if result_num > 0:
            for i in range(result_num):
                parent_instance.ps4_buttons.right(sleep_after=.5)
        elif result_num < 0:
            for i in range(abs(result_num)):
                parent_instance.ps4_buttons.left(sleep_after=.5)
        # if character.isupper():
        #     parent_instance.ps4_buttons.l3()
        # if select_character[2] == 1:
        #     parent_instance.ps4_buttons.l2()
        parent_instance.ps4_buttons.cross()
        # if select_character[2] == 1:
        #     parent_instance.ps4_buttons.l2()
        current_character = double_check_keyboard.get(character.lower())


def json_file_check_2(player, player_asset_id):
    temp_id_name = player['id']
    player_full_name = player_c = player_f = player_l = player_r = player_id = ''
    if str(temp_id_name) == str(player_asset_id):
        player_full_name = player['f'] + ' ' + player['l']
        player_c = player.get('c', '')
        player_f = player['f']
        player_l = player['l']
        player_r = player['r']
        player_id = player['id']

    return player_full_name, player_c, player_f, player_l, player_r, player_id


def json_file_check(player, player_asset_id, need_first_name=False):
    temp_f_name = player['f'].lower()
    temp_l_name = player['l'].lower()
    try:
        temp_c_name = player['c'].lower()
    except:
        temp_c_name = ''
    temp_id_name = player['id']
    player_name = ''
    if str(temp_id_name) == str(player_asset_id):
        if temp_c_name:
            if need_first_name:
                player_name = temp_f_name + ' ' + temp_c_name
            else:
                player_name = temp_c_name
        else:
            player_name = temp_f_name + ' ' + temp_l_name
        # contains = 0
        # for each_part in player_name.split():
        #     if temp_f_name.find(each_part) != -1:
        #         contains = 1
        # if not contains:
        #     player_name = temp_f_name + ' ' + player_name
    return player_name


def get_player_data_by_asset_id(player_asset_id=''):
    players_file = open(os.path.join(BASE_DIR, 'utils/players.json'), encoding='utf-8')
    players_data = players_file.read()
    players_file.close()
    players_data = json.loads(players_data)
    player_name = ''  # first name + last name
    player_c = ''  # special name
    player_f = ''  # first name
    player_l = ''  # last name
    player_r = ''  # rate
    player_id = ''  # asset id
    for player in players_data['LegendsPlayers']:
        player_name, player_c, player_f, player_l, player_r, player_id = json_file_check_2(player, player_asset_id)
        if player_name:
            return player_name, player_c, player_f, player_l, player_r, player_id

    if not player_name:
        for player in players_data['Players']:
            player_name, player_c, player_f, player_l, player_r, player_id = json_file_check_2(player, player_asset_id)
            if player_name:
                return player_name, player_c, player_f, player_l, player_r, player_id
    # print result_list
    return player_name, player_c, player_f, player_l, player_r, player_id


def get_player_fifa_name_by_id(player_asset_id='', need_first_name=False):
    players_file = open(os.path.join(BASE_DIR, 'utils/players.json'), encoding='utf-8')
    players_data = players_file.read()
    players_file.close()
    players_data = json.loads(players_data)
    player_name = ''
    for player in players_data['LegendsPlayers']:
        player_name = json_file_check(player, player_asset_id, need_first_name=need_first_name)
        if player_name:
            return player_name

    if not player_name:
        for player in players_data['Players']:
            player_name = json_file_check(player, player_asset_id, need_first_name=need_first_name)
            if player_name:
                return player_name
    # print result_list
    return player_name


def get_team_links_from_file():
    with open(os.path.join(BASE_DIR, 'utils/teamlinks.json'), encoding='utf-8') as teams_file:
        return json.loads(teams_file.read())


def clear_outbid(fifa_account, se, headers, trade_ids):
    options_header = {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'en-US,en;q=0.5',
        'Connection': 'keep-alive',
        'Host': fifa_host,
        'Access-Control-Request-Headers': 'content-type,x-ut-sid',
        'Access-Control-Request-Method': 'DELETE',
        'Origin': 'https://www.ea.com',
        'Referer': 'https://www.ea.com/',
        'User-Agent': user_agent
    }
    se.options(
        f'{fifa_23_address}/watchlist?tradeId={trade_ids}',
        headers=options_header)
    resp = se.delete(
        f'{fifa_23_address}/watchlist?tradeId={trade_ids}',
        headers=headers)
    new_print(fifa_account, 'clear outbid = ',
              f'{fifa_23_address}/watchlist?tradeId={trade_ids}')
    return resp


def get_credit_web(account_id, se, header, options_header=None, active_trades=False, expire_trades=False):
    if options_header is None:
        options_header = {}
    fifa_account = FifaAccount.objects.get(id=account_id)
    new_print(fifa_account, 'get credit : ', fifa_account)
    resp = se.get(f'{fifa_23_address}/watchlist', headers=header)
    json_resp = resp.json()
    current_credit = json_resp['credits']
    credit = current_credit
    resp = get_trade_pile_2(fifa_account, se, options_header=options_header, header=header)
    json_resp = resp.json()
    trades = json_resp.get('auctionInfo', [])
    if active_trades:
        sum_buy_now = 0
        for trade in trades:
            if trade['tradeState'] == 'active':
                sum_buy_now += trade['buyNowPrice']
        sum_buy_now = sum_buy_now - ((sum_buy_now * 5) / 100)
        credit = credit + sum_buy_now
    if expire_trades:
        sum_buy_now_2 = 0
        for trade in trades:
            if trade['tradeState'] == 'expired':
                sum_buy_now_2 += trade['buyNowPrice']
        sum_buy_now_2 = sum_buy_now_2 - ((sum_buy_now_2 * 5) / 100)
        credit = credit + sum_buy_now_2
    return {'credits': current_credit, 'plus_credit': credit}


def clim_lvlup_objectives_milestones(fifa_account, se, header, fcas_sid,
                                     clim_lvlup=True, clim_objectives_milestones=True):
    new_print(fifa_account, 'clim_lvlup_objectives_milestones header ',
              header, ' fcas_sid ', fcas_sid, ' clim_lvlup ', clim_lvlup,
              ' clim_objectives_milestones ', clim_objectives_milestones,
              )
    if clim_lvlup and fcas_sid:
        new_print(fifa_account, 'clim level up rewards')
        # clim level up rewards ( objectives )
        # new_print(fifa_account, 'clim level up not fixed , fix me')
        copy_header = copy.deepcopy(header)
        copy_header.update({
            'Host': fifa_host_2,
            'X-Fc-Sid': fcas_sid,
        })
        resp = se.get(f'{fifa_23_address_2}/user/season', headers=copy_header)
        save_account_request(
            fifa_account=fifa_account,
            link=f'{fifa_23_address}/scmp/campaign?type=active',
        )
        levelup_rewards = resp.json()
        season_title = levelup_rewards['name']
        current_xp = levelup_rewards['currentXP']
        rewards = levelup_rewards['passes'][0]['levels']
        season_id = levelup_rewards['seasonId']
        for reward in rewards:
            select_option_id = 0
            cliam_level = reward['level']
            season_progress_special_option = ObjectiveSeasonProgressSpecialOption.objects.filter(
                xp_threshold=int(reward['completeXP']),
                title=season_title
            ).last()
            if season_progress_special_option:
                select_option_id = season_progress_special_option.option_id
            else:
                ObjectiveSeasonProgressSpecialOption.objects.get_or_create(
                    xp_threshold=int(reward['completeXP']),
                    title=season_title
                )
            if reward['completeXP'] < current_xp:
                if reward.get('status', 0) != 2:
                    claim_reward_link = f'{fifa_23_address_2}/user/season/reward/claim?seasonId={season_id}'
                    if select_option_id:
                        claim_data = {"claimRewardRequestDtos": [{
                            "sourceId": cliam_level, "source": "SEASON", "value": select_option_id}]}
                    else:
                        claim_data = {"claimRewardRequestDtos": [{"sourceId": cliam_level, "source": "SEASON"}]}
                    resp = se.post(
                        claim_reward_link,
                        data=json.dumps(claim_data),
                        headers=copy_header)
                    save_account_request(
                        fifa_account=fifa_account,
                        link=f'{fifa_23_address_2}/user/season/reward/claim?seasonId={season_id},{select_option_id}',
                    )
                    new_print(fifa_account, 'get season object : ', claim_reward_link,
                              ' -- resp : ', resp.text)
                    time.sleep(2)
        se.put(f'{fifa_23_address_2}/season/auto/grant?type=ALL', header)
        # time.sleep(2)
        # resp = se.get(f'{fifa_23_address}/scmp/campaign?type=active',
        #     headers=header)
        # save_account_request(
        #     fifa_account=fifa_account,
        #     link=f'{fifa_23_address}/scmp/campaign?type=active',
        # )
        # levelup_rewards = resp.json()
        # time.sleep(2)
        # season_title = levelup_rewards['title']
        # xp = levelup_rewards['xp']
        # rewards = levelup_rewards['scmpChosenRewardDtos']
        # new_print(fifa_account, 'claim levelup rewards')
        # for reward in rewards:
        #     select_option_id = 0
        #     season_progress_special_option = ObjectiveSeasonProgressSpecialOption.objects.filter(
        #         xp_threshold=int(reward['xpThreshold']),
        #         title=season_title
        #     ).last()
        #     if season_progress_special_option:
        #         select_option_id = season_progress_special_option.option_id
        #     else:
        #         ObjectiveSeasonProgressSpecialOption.objects.get_or_create(
        #             xp_threshold=int(reward['xpThreshold']),
        #             title=season_title
        #         )
        #     if reward['xpThreshold'] < xp:
        #         if reward.get('state', 0) != 2:
        #             resp = se.put(
        #                 f'{fifa_23_address}/scmp/campaign/level/{reward["levelId"]}/reward/{select_option_id}',
        #                 headers=header)
        #             save_account_request(
        #                 fifa_account=fifa_account,
        #                 link=f'{fifa_23_address}/scmp/campaign/level/%s/reward/{select_option_id}',
        #             )
        #             new_print(fifa_account, 'get season object : ',
        #                       f'{fifa_23_address}/scmp/campaign/level/{reward["levelId"]}/reward/{select_option_id}',
        #                       ' -- resp : ', resp.text)
        #             time.sleep(2)
    if clim_objectives_milestones:
        new_print(fifa_account, 'clim objectives and milestone')
        # clim previous session objectives
        resp4 = se.put(
            f'{fifa_23_address}/scmp/campaign/rewards/all',
            headers=header)
        resp4 = se.put(
            f'{fifa_23_address}/scmp/learning/campaign/rewards/all',
            headers=header)
        # clim objectives and milestones rewards
        resp2 = se.get(
            # f'{fifa_23_address}/scmp/campaign/categories',
            f'{fifa_23_address}/scmp/objective/categories/all',
            headers=header)
        save_account_request(
            fifa_account=fifa_account,
            link=f'{fifa_23_address}/scmp/objective/categories/all',
        )
        objectives_milestons = resp2.json()
        for category in objectives_milestons:
            category_id = category['categoryId']
            category_name = category['name']
            category_type = category['type']
            for group_item in category['groupsList']:
                group_id = group_item["groupId"]
                group_state = group_item['groupState']
                group_title = group_item['title']
                group_objectives = group_item.get('objectives', [])
                group_times_completed = group_item.get('timesCompleted', 0)
                group_repeats = group_item.get('repeats', 0)
                if int(group_state) >= 1:
                    need_to_clime_all = False
                    for object_item in group_objectives:
                        if object_item.get('state') == 'COMPLETED':
                            need_to_clime_all = True
                            break
                    if need_to_clime_all or group_state == 2:
                        url_2 = f'{fifa_23_address}/scmp/learning/category/{category_id}/group/{group_id}'
                        save_account_request(fifa_account=fifa_account, link=url_2)
                        resp6 = se.get(url_2, headers=header)
                        new_print(fifa_account, 'need to clime objective : ', group_title, ' from ', category_name,
                                  ' status code : ', resp6.status_code)
                        url_3 = f'{fifa_23_address}/scmp/campaign/group/{group_id}/rewards/all?groupType={category_type}'
                        resp7 = se.put(url_3, headers=header)
                        new_print(fifa_account, 'claiming objective : ', group_title, ' from ', category_name,
                                  ' clime status : ', resp7.status_code)
                        time.sleep(2)



                # if category_id == 1:
                #     url_1 = f'{fifa_23_address}/scmp/campaign/category/{category_id}/group/{group_id}'
                #
                # elif category_id == 2:
                #     url_1 = f'{fifa_23_address}/scmp/learning/category/{category_id}/group/{group_id}'
                # else:
                #     # new_print(fifa_account, '')
                #     continue

                # if group_item.get('objectivesCompleted', 0) > 0:
                #     resp5 = se.get(url_1, headers=header)
                #     save_account_request(fifa_account=fifa_account, link=url_1)
                #     # new_print(fifa_account,
                #     #           'objective url : ', url_1,
                #     #           # 'resp : ', resp5.text
                #     #           )
                #     time.sleep(2)
                #
                #     json_resp5 = resp5.json()
                #     for objective in json_resp5.get('objectives', []):
                #         if objective.get('state', '') in ['COMPLETED', 'XP_REDEEMED']:
                #             if category_id == 1:
                #                 url_3 = f'{fifa_23_address}/scmp/campaign/group/{group_id}/objective/{objective.get("objectiveId")}/rewards'
                #             else:
                #                 url_3 = f'{fifa_23_address}/scmp/learning/group/{group_id}/objective/{objective.get("objectiveId")}/rewards'
                #             resp4 = se.put(
                #                 url_3,
                #                 headers=header
                #             )
                #             save_account_request(
                #                 fifa_account=fifa_account,
                #                 link=url_3,
                #             )
                #             # new_print(fifa_account, 'objective resp 4 : ', url_3, resp4.text)
                #             time.sleep(2)
                #     if (group_item['objectivesNumber'] == group_item.get('objectivesCompleted', 0) and
                #             group_item.get('groupState', 0) == 2):
                #         if category_id == 1:
                #             url_2 = f'{fifa_23_address}/scmp/campaign/group/{group_id}/rewards'
                #         else:
                #             url_2 = f'{fifa_23_address}/scmp/learning/group/{group_id}/rewards'
                #         resp3 = se.put(
                #             url_2,
                #             headers=header
                #         )
                #         save_account_request(
                #             fifa_account=fifa_account,
                #             link=url_2,
                #         )
                #         # new_print(fifa_account, 'objective resp 3 :', url_2, resp3.text)
                #         time.sleep(2)


def get_previous_price_grade(price):
    price = int(price)
    if price <= 1000:
        return price - 50
    elif price <= 10000:
        return price - 100
    elif price <= 50000:
        return price - 250
    elif price <= 100000:
        return price - 500
    else:
        return price - 1000


def get_next_price_grade(price):
    price = int(price)
    if price < 1000:
        return price + 50
    elif price < 10000:
        return price + 100
    elif price < 50000:
        return price + 250
    elif price < 100000:
        return price + 500
    else:
        return price + 1000


def get_round_price(price):
    price = int(price)
    if price < 1000:
        diff = price % 50
        return int(price - diff)
    elif price < 10000:
        diff = price % 100
        return int(price - diff)
    elif price < 50000:
        diff = price % 250
        return int(price - diff)
    elif price < 100000:
        diff = price % 500
        return int(price - diff)
    else:
        diff = price % 1000
        return int(price - diff)


def get_round_top_price(price):
    price = int(price)
    if price > 100000:
        diff = price % 1000
        if diff == 0:
            diff = 1000
        return int(price + (1000 - diff))
    elif price > 50000:
        diff = price % 500
        if diff == 0:
            diff = 500
        return int(price + (500 - diff))
    elif price > 10000:
        diff = price % 250
        if diff == 0:
            diff = 250
        return int(price + (250 - diff))
    elif price > 1000:
        diff = price % 100
        if diff == 0:
            diff = 100
        return int(price + (100 - diff))
    else:
        diff = price % 50
        if diff == 0:
            diff = 50
        return int(price + (50 - diff))


def most_common(lst):
    return max(set(lst), key=lst.count)


class ThreadWithReturnValue(Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None,
                 raise_on_exception=False):
        Thread.__init__(self, group, target, name, args, kwargs, daemon=daemon)

        self._return = None
        self.exc = None
        self.raise_on_exception = raise_on_exception

    def run(self):
        if self._target is not None:
            try:
                self._return = self._target(*self._args, **self._kwargs)
            except BaseException as e:
                self.exc = e

    def join(self):
        Thread.join(self)
        if self.exc and self.raise_on_exception:
            raise self.exc
        return self._return


def get_last_email(imap_user, imap_pass, imap_host, email_count=1):
    mail_subject = ''
    mail_from = ''
    message_time = ''
    mail_content = ''
    emails_list = []
    for iii in range(5):
        try:
            imap = imaplib.IMAP4_SSL(imap_host, timeout=100)
            break
        except:
            if iii == 4:
                imap = imaplib.IMAP4_SSL(imap_host, timeout=100)
            print('cant connect to imap , try again : ', iii)
    try:
        imap.login(imap_user, imap_pass)
    except Exception as error2:
        if 'LOGIN failed' in str(error2):
            return {
                'subject': None,
                'from': None,
                'time': timezone.localtime(),
                'body': None,
                'error': str(error2),
                'traceback': str(traceback.format_exc()),
                'emails_list': emails_list,
            }
        else:
            raise error2
    status, messages_list = imap.select('Inbox')
    message_numbers = reversed(range(1, int(messages_list[0])+1))
    for email_item in message_numbers:
        messages = email_item
        try:
            result, msg = imap.fetch(str(messages), "(RFC822)")
        except Exception as error:
            if ('Invalid messageset' in str(error) or
                    'The specified message set is invalid' in str(error) or
                    'User is authenticated but not connected' in str(error) or
                    'getaddrinfo failed' in str(error) or
                    'LOGIN failed' in str(error)
            ):
                return {
                    'subject': None,
                    'from': None,
                    'time': timezone.localtime(),
                    'body': None,
                    'error': str(error),
                    'traceback': str(traceback.format_exc()),
                    'emails_list': emails_list,
                }
            else:
                raise error
        for response in msg:
            if isinstance(response, tuple):
                # parse a bytes email into a message object
                msg = email.message_from_bytes(response[1])
                # decode the email subject
                subject, encoding = decode_header(msg["Subject"])[0]
                if isinstance(subject, bytes):
                    # if it's a bytes, decode to str
                    subject = subject.decode(encoding)
                email_time, encoding = decode_header(msg.get('Date'))[0]
                if isinstance(email_time, bytes):
                    email_time = email_time.decode(encoding)
                localtz = pytz.timezone('Asia/Tehran')
                message_time = localtz.normalize(parsedate_to_datetime(email_time).astimezone(localtz))
                message = email.message_from_bytes(response[1])

                # with the content we can extract the info about
                # who sent the message and its subject
                mail_from = message['from']
                mail_subject = message['subject']

                # then for the text we have a little more work to do
                # because it can be in plain text or multipart
                # if its not plain text we need to separate the message
                # from its annexes to get the text
                if message.is_multipart():
                    mail_content = ''

                    # on multipart we have the text message and
                    # another things like annex, and html version
                    # of the message, in that case we loop through
                    # the email payload
                    for part in message.get_payload():
                        # if the content type is text/plain
                        # we extract it
                        if part.get_content_type() == 'text/plain':
                            mail_content += part.get_payload()
                else:
                    # if the message isn't multipart, just extract it
                    mail_content = message.get_payload()
        emails_list.append({
        'subject': mail_subject,
        'from': mail_from,
        'time': message_time,
        'body': mail_content})
        if email_count <= len(emails_list):
            break

    imap.close()
    imap.logout()
    return {
        'subject': mail_subject,
        'from': mail_from,
        'time': message_time,
        'body': mail_content,
        'emails_list': emails_list,
    }


def focus_on_ps(fifa_account: FifaAccount):
    if fifa_account.platform == 'ps':
        system_order = '"C:\Program Files (x86)\Sony\PS Remote Play\RemotePlay.exe"'
        print(system_order)
        os.system(system_order)
    elif fifa_account.platform in ['xboxs', 'xbox360']:
        # system_order = '"XboxPcApp.exe"'
        # print(system_order)
        # os.system(system_order)
        desktop = os.path.expanduser("~/Desktop")
        print(os.path.join(desktop, 'Xbox.lnk'))
        os.system(os.path.join(desktop, 'Xbox.lnk'))


def get_image_position(small_image_name, large_image_name):
    # http://www.learningaboutelectronics.com/Articles/How-to-match-an-image-embedded-in-another-image-Python-OpenCV.php
    image = cv2.imread(large_image_name)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    template = cv2.imread(small_image_name, 0)
    result = cv2.matchTemplate(gray, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    height, width = template.shape[:2]
    top_left = max_loc
    top_right = (top_left[0] + width, top_left[1])
    bottom_left = (top_left[0], top_left[1] + height)
    bottom_right = (top_left[0] + width, top_left[1] + height)
    # cv2.rectangle(image, top_left, bottom_right, (0, 0, 255), 5)
    # cv2.imshow('Rainforest', image)
    # cv2.waitKey(0)
    return {
        'top_left': top_left, 'top_right': top_right,
        'bottom_left': bottom_left, 'bottom_right': bottom_right,
        'width': width, 'height': height
    }


def check_bot_version():
    try:
        program_version = requests.get('http://142.132.177.244:8000/accounts/get-last-version/').json()
    except:
        print('can`t get version : ', traceback.format_exc())
        return
    try:
        current_version = open('version.txt', 'r')
    except:
        default_version = open('version.txt', 'w')
        default_version.write('0')
        default_version.close()
        current_version = open('version.txt', 'r')
    current_version = current_version.read()
    if str(program_version.get('number')) != str(current_version):
        # if False:
        print('need to update program')
        return 'need update bot'


def get_current_connections_to_database(database_name=None):
    if database_name:
        connection_obj = connections[database_name]
    else:
        connection_obj = connection
    with connection_obj.cursor() as cursor:
        cursor.execute("select count(*) from pg_stat_activity;")
        current_connections_count = cursor.fetchone()[0] or 0
        cursor.close()
    return current_connections_count


def pin_events_creator(fifa_account, se: Session, source, persona_id, nucleus_id, sid, platform='xbsx', counter=0):
    now_time = str(datetime.datetime.utcnow().isoformat()[:-3] + 'Z')
    header = {'Content-Type': 'application/json',
              'Origin': 'https://www.ea.com',
              'Referer': 'https://www.ea.com/',
              'User-Agent': user_agent,
              'Accept': '*/*',
              'Accept-Encoding': 'gzip, deflate, br',
              'Accept-Language': 'en-US,en;q=0.5',
              'Connection': 'keep-alive',
              'x-ea-game-id': fut_web_number,
              'x-ea-game-id-type': 'easku',
              'x-ea-taxv': '1.1'
              }
    example_data = {
        "custom": {
            "networkAccess": "G",
            "service_plat": platform
        },
        "et": "client",
        "events": [
            {
                "status": "success",
                # "source": source,
                "pgid": source,
                "type": "menu",
                "core": {
                    "s": counter,
                    "pidt": "persona",
                    "pid": str(persona_id),
                    "ts_event": now_time,
                    "en": "page_view",
                    "pidm": {
                        "nucleus": int(nucleus_id)
                    }
                }
            }
        ],
        "gid": 0,
        "is_sess": True,
        "loc": "en-US",
        "plat": "web",
        "rel": "prod",
        "sid": sid,
        "taxv": "1.1",
        "tid": fut_web_number,
        "tidt": "easku",
        "ts_post": now_time,
        # todo : make bellow dynamic
        "v": "25.0.0"
    }
    pin_result = se.post(pin_event_url, data=json.dumps(example_data), headers=header)
    new_print(fifa_account, 'pin event , data : ', example_data, ' result : ', pin_result, ' text : ', pin_result.text)
    return example_data


def telegram_send_photo(fifa_account: FifaAccount, photo_path, caption='', message_type=None, message_thread_id=None):
    close_old_connections()
    TelegramMessage.objects.create(
        fifa_account=fifa_account,
        message_type=message_type,
        text=caption
    )
    telbot = telepot.Bot(FIFA_REPORT_TOKEN)
    with open(photo_path, 'rb') as photo_file:
        # telbot.sendPhoto(chat_id='-1001711538724', photo=photo_file, caption=caption)
        data = {
            'chat_id': ARZBAZI_REPORT_GROUP_ID,
            'caption': caption,
        }
        if message_thread_id:
            data.update({'message_thread_id': message_thread_id})
        send_photo_url = f'https://api.telegram.org/bot{FIFA_REPORT_TOKEN}/sendPhoto'
        send_photo_result = requests.post(send_photo_url, data=data, files={"photo": photo_file})
        new_print(fifa_account, 'send photo result : ',
                  send_photo_result.status_code, ' -- ', send_photo_result.text)

    if fifa_account.creator not in django_user.objects.filter(
            id__in=[18, ]
    ) and TelegramMessage.objects.filter(
        fifa_account=fifa_account,
        create_time__gte=timezone.localtime() - timezone.timedelta(hours=24),
        text=caption).count() <= 1 and message_type == 'error':
        chat_id = '-1001802370673' # گروه اجرایی فات پلاس
        time.sleep(2)
        with open(photo_path, 'rb') as photo_file:
            telbot.sendPhoto(chat_id=chat_id, photo=photo_file, caption=caption)
    return send_photo_result


def calculate_player_tax(current_price, min_price):
    return (((current_price + min_price)*.05) / (current_price - min_price)) * 100


# def get_card_from_mydgn(fifa_account: FifaAccount, deactive_mule: MuleDischargeMode2, credit=0,
#                         login_again_counter=0):
#     new_print(fifa_account, 'getting card with price : ', credit, ' mule : ', deactive_mule.user_name,
#               ' login_again_counter : ', login_again_counter)
#     import websocket
#     if login_again_counter > 5:
#         return {}
#     mydgn_session = cloudscraper.create_scraper(browser={
#         'browser': 'firefox',
#         'platform': 'linux',
#         'mobile': False
#     })
#     firs_page_text = mydgn_session.get('https://www.mydgn.com/').text
#     token = re.search(r'name="_token" value="(.+)">', firs_page_text).group(1)
#     time.sleep(2)
#
#     login_resp = mydgn_session.post(
#         'https://www.mydgn.com/login',
#         json={
#             "_token": token,
#             "ses_id": "eyJjbGllbnQiOnsidHlwZSI6ImJyb3dzZXIiLCJuYW1lIjoiQ2hyb21lIiwidmVyc2lvbiI6IjExOS4wIiwiZW5naW5lIjoiQmxpbmsiLCJlbmdpbmVWZXJzaW9uIjoiIn0sIm9zIjp7Im5hbWUiOiJXaW5kb3dzIiwidmVyc2lvbiI6IjEwLjAiLCJwbGF0Zm9ybSI6Ing2NCJ9LCJkZXZpY2UiOnsidHlwZSI6ImRlc2t0b3AiLCJicmFuZCI6IiIsIm1vZGVsIjoiIiwid2lkdGgiOjE5MjAsImhlaWdodCI6MTA0MCwiY3B1Ijo0LCJyYW0iOjgsImNvb2tpZV9lbmFibGVkIjp0cnVlLCJ1c2VyX2FnZW50IjoiTW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzExOS4wLjAuMCBTYWZhcmkvNTM3LjM2IiwibGFuZ3VhZ2UiOiJlbi1HQiIsImxhbmd1YWdlcyI6WyJlbi1HQiIsImVuLVVTIiwiZW4iXX0sImJvdCI6bnVsbH0=",
#             "email": deactive_mule.user_name,
#             "password": deactive_mule.password, "remember": "on"})
#     time.sleep(2)
#     resp = mydgn_session.get('https://www.mydgn.com/account')
#     csrf_token = re.search(r'window.csrf_token = "(.+)"', resp.text).group(1)
#     sup_id = re.search(r"let sup_id = '(.+)'", resp.text).group(1)
#     time.sleep(2)
#
#     ws = websocket.create_connection("wss://www.mydgn.com:2053/socket.io/?EIO=3&transport=websocket", header={
#         'Host': 'www.mydgn.com:2053',
#         'Connection': 'Upgrade',
#         'Pragma': 'no-cache',
#         'Cache-Control': 'no-cache',
#         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
#         'Upgrade': 'websocket',
#         'Origin': 'https://www.mydgn.com',
#         'Sec-WebSocket-Version': '13',
#         'Accept-Encoding': 'gzip, deflate, br',
#         'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8',
#         'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
#     })
#     ws.recv()
#     ws.recv()
#     ws.send(
#         '42["subscribe",{"channel":"mydgn_database_supplier.'+str(sup_id)+'","auth":{"headers":{}}}]')
#     ws.send('42["subscribe",{"channel":"mydgn_database_auction","auth":{"headers":{}}}]')
#     ws.send(
#         '42["subscribe",{"channel":"mydgn_database_supplier_notification.'+str(sup_id)+'","auth":{"headers":{}}}]')
#     target_data = {}
#     for i in range(90):
#         if i % 5 == 0:
#             ws.send('2')
#             new_print(fifa_account, 'send 2')
#         try:
#             result = ws.recv()
#         except websocket.WebSocketConnectionClosedException:
#             new_print(fifa_account, 'connection closed')
#             return get_card_from_mydgn(fifa_account=fifa_account, deactive_mule=deactive_mule, credit=credit,
#                                        login_again_counter=login_again_counter + 1)
#         if str(result).startswith('42'):
#             json_result = json.loads(result[2:])
#             card_data = json_result[2]['data']
#             if card_data.get('resource_id'):
#                 allowed_in_sec = card_data['allowed_in_sec']
#                 avg_price = card_data['avg_price']
#                 chemistry_style = card_data['chemistry_style']
#                 contracts = card_data['contracts']
#                 created_at_timestamp = card_data['created_at_timestamp']
#                 ea_trade_id = card_data['ea_trade_id']
#                 end_price = card_data['end_price']
#                 futbin_id = card_data['futbin_id']
#                 futbin_link = card_data['futbin_link']
#                 mydgn_id = card_data['id']
#                 left_time_ea_in_sec = card_data['left_time_ea_in_sec']
#                 level = card_data['level']
#                 name = card_data['name']
#                 owners = card_data['owners']
#                 pick_block_ms = card_data['pick_block_ms']
#                 platform_name = card_data['platform_name']
#                 position = card_data['position']
#                 price = card_data['price']
#                 resource_id = card_data['resource_id']
#                 start_price = card_data['start_price']
#                 status = card_data['status']
#                 if end_price < credit and status == 'open' and platform_name == 'console':
#                     new_print(fifa_account, status, ' ', allowed_in_sec, ' ', name, ' platform :', platform_name,
#                           ' page : ', f'https://www.mydgn.com/auctions/pick/{mydgn_id}')
#                     # time.sleep(5)
#                     custom_header = mydgn_session.headers.__dict__
#                     custom_header.update({
#                         'X-Csrf-Token': csrf_token
#                     })
#                     resp = mydgn_session.post(
#                         f'https://www.mydgn.com/auctions/pick/{mydgn_id}', json={"platform_name": "console"},
#                         headers=custom_header)
#                     new_print(fifa_account, 'set buy sign : ', resp.status_code, resp.text)
#                     try:
#                         json_resp = resp.json()
#                     except:
#                         json_resp = {}
#                     if resp.status_code == 200 and json_resp.get('status') != 'error':
#                         target_data = {
#                             'mydgn_session': mydgn_session,
#                             'mydgn_id': mydgn_id,
#                             'resource_id': resource_id,
#                             'futbin_id': futbin_id,
#                             'futbin_link': futbin_link,
#                             'name': name,
#                             'level': level,
#                             'left_time_ea_in_sec': left_time_ea_in_sec,
#                             'end_price': end_price,
#                             'avg_price': avg_price,
#                             'price': price,
#                             'start_price': start_price,
#                             'csrf_token': csrf_token,
#                         }
#                         break
#                     else:
#                         new_print(fifa_account, 'can not set buy item , ', resp.status_code, resp.text)
#         time.sleep(2)
#     ws.close()
#     return target_data


def get_card_from_mydgn(parent_instance, fifa_account: FifaAccount, deactive_mule: MuleDischargeMode2, credit=0,
                        login_again_counter=0, bad_asset_ids=[]):
    new_print(fifa_account, 'getting card from api with price : ', credit, ' mule : ', deactive_mule.user_name,
              ' login_again_counter : ', login_again_counter)
    if login_again_counter > 5:
        return {}
    discharge_lowest_target_price = ConsoleBotSetting.objects.get(
        name='discharge_with_mode2_mydgn_lowest_target_buy_now_price').int_value
    discharge_with_mode2_highest_tax = ConsoleBotSetting.objects.get(name='discharge_with_mode2_highest_tax').int_value
    if deactive_mule.is_api is False:
        import websocket
        if login_again_counter > 5:
            return {}
        mydgn_session = cloudscraper.create_scraper(browser={
            'browser': 'firefox',
            'platform': 'linux',
            'mobile': False
        })
        firs_page_text = mydgn_session.get('https://www.mydgn.com/').text
        token = re.search(r'name="_token" value="(.+)">', firs_page_text).group(1)
        time.sleep(2)

        login_resp = mydgn_session.post(
            'https://www.mydgn.com/login',
            json={
                "_token": token,
                "ses_id": "eyJjbGllbnQiOnsidHlwZSI6ImJyb3dzZXIiLCJuYW1lIjoiQ2hyb21lIiwidmVyc2lvbiI6IjExOS4wIiwiZW5naW5lIjoiQmxpbmsiLCJlbmdpbmVWZXJzaW9uIjoiIn0sIm9zIjp7Im5hbWUiOiJXaW5kb3dzIiwidmVyc2lvbiI6IjEwLjAiLCJwbGF0Zm9ybSI6Ing2NCJ9LCJkZXZpY2UiOnsidHlwZSI6ImRlc2t0b3AiLCJicmFuZCI6IiIsIm1vZGVsIjoiIiwid2lkdGgiOjE5MjAsImhlaWdodCI6MTA0MCwiY3B1Ijo0LCJyYW0iOjgsImNvb2tpZV9lbmFibGVkIjp0cnVlLCJ1c2VyX2FnZW50IjoiTW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzExOS4wLjAuMCBTYWZhcmkvNTM3LjM2IiwibGFuZ3VhZ2UiOiJlbi1HQiIsImxhbmd1YWdlcyI6WyJlbi1HQiIsImVuLVVTIiwiZW4iXX0sImJvdCI6bnVsbH0=",
                "email": deactive_mule.user_name,
                "password": deactive_mule.password, "remember": "on"})
        time.sleep(2)
        resp = mydgn_session.get('https://www.mydgn.com/account')
        csrf_token = re.search(r'window.csrf_token = "(.+)"', resp.text).group(1)
        sup_id = re.search(r"let sup_id = '(.+)'", resp.text)
        if sup_id:
            sup_id = sup_id.group(1)
        else:
            new_print(fifa_account, 'can not get sup_id , sleep 5 min')
            time.sleep(300)
            return {}
        try:
            first_page = mydgn_session.get('https://www.mydgn.com/')
            current_balance = re.search('class=\"balance\">(.+)</span>', first_page.text).group(1)
            deactive_mule.refresh_from_db()
            deactive_mule.available_payment = str(current_balance)[:50]
            deactive_mule.save()
        except:
            new_print(fifa_account, 'except in mydgn available payment : ', traceback.format_exc())
        time.sleep(2)

        ws = websocket.create_connection("wss://www.mydgn.com:2053/socket.io/?EIO=3&transport=websocket", header={
            'Host': 'www.mydgn.com:2053',
            'Connection': 'Upgrade',
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
            'Upgrade': 'websocket',
            'Origin': 'https://www.mydgn.com',
            'Sec-WebSocket-Version': '13',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8',
            'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
        })
        ws.recv()
        ws.recv()
        ws.send(
            '42["subscribe",{"channel":"mydgn_database_supplier.' + str(sup_id) + '","auth":{"headers":{}}}]')
        ws.send('42["subscribe",{"channel":"mydgn_database_auction","auth":{"headers":{}}}]')
        ws.send(
            '42["subscribe",{"channel":"mydgn_database_supplier_notification.' + str(
                sup_id) + '","auth":{"headers":{}}}]')
        target_data = {}
        upp_tax_cards = []
        for i in range(5):
            if i % 5 == 0:
                ws.send('2')
                new_print(fifa_account, 'send 2')
                fifa_account.refresh_from_db()
                if fifa_account.run_discharge is False:
                    return target_data
            try:
                result = ws.recv()
            except websocket.WebSocketConnectionClosedException:
                new_print(fifa_account, 'connection closed')
                return get_card_from_mydgn(fifa_account=fifa_account, deactive_mule=deactive_mule,
                                           credit=credit,
                                           login_again_counter=login_again_counter + 1)
            if str(result).startswith('42'):
                json_result = json.loads(result[2:])
                card_data = json_result[2]['data']
                if card_data.get('resource_id'):
                    allowed_in_sec = card_data['allowed_in_sec']
                    avg_price = card_data['avg_price']
                    chemistry_style = card_data['chemistry_style']
                    contracts = card_data['contracts']
                    created_at_timestamp = card_data['created_at_timestamp']
                    ea_trade_id = card_data['ea_trade_id']
                    end_price = card_data['end_price']
                    futbin_id = card_data['futbin_id']
                    futbin_link = card_data['futbin_link']
                    mydgn_id = card_data['id']
                    left_time_ea_in_sec = card_data['left_time_ea_in_sec']
                    expire_time_stamp = int(card_data['created_at_timestamp']) + int(card_data['left_time_ea_in_sec'])
                    level = card_data['level']
                    name = card_data['name']
                    owners = card_data['owners']
                    pick_block_ms = card_data['pick_block_ms']
                    platform_name = card_data['platform_name']
                    position = card_data['position']
                    price = card_data['price']
                    resource_id = card_data['resource_id']
                    start_price = card_data['start_price']
                    status = card_data['status']
                    if {'resource_id': resource_id, 'avg_price': avg_price, 'end_price': end_price} in upp_tax_cards:
                        new_print(fifa_account, 'this card in upp tax cards : ', card_data)
                        continue
                    blocked_players = ConsoleSpecialNames.objects.filter(
                        Q(Q(edited_name='') | Q(edited_name=None)) & Q(Q(compare_name='') | Q(compare_name=None)),
                        player_name=name)
                    if blocked_players:
                        new_print(fifa_account, 'this player has bad name and has not fixed name 2 , ', name,
                                  blocked_players)
                        continue
                    if int(end_price) < discharge_lowest_target_price:
                        new_print(fifa_account, f'buy now price less than lowest valid , ',
                                  end_price, ' , ', discharge_lowest_target_price)
                        continue
                    try:
                        futbin_result = parent_instance.get_price_from_futbin_and_futwiz(resource_id, wait_on_error=10)
                        futbin_first_price = futbin_result.get('first_price')
                    except:
                        new_print(fifa_account, 'cant get data from futbin : ', traceback.format_exc()[:10000])
                        time.sleep(10)
                        continue
                    numerator = int(futbin_first_price) * .05 + int(end_price) * .05
                    current_tax = int(((numerator + avg_price - futbin_first_price) / (numerator + int(end_price) - int(avg_price))) * 100)
                    if current_tax > discharge_with_mode2_highest_tax:
                        new_print(fifa_account, f'current tax higher than allowed tax 1, ',
                                  current_tax, ' , ', discharge_with_mode2_highest_tax)
                        upp_tax_cards.append(
                            {'resource_id': resource_id, 'avg_price': avg_price, 'end_price': end_price})
                        continue
                    new_print(fifa_account, 'current card tax : ', current_tax)
                    if end_price < credit and status == 'open' and platform_name == 'console':
                        new_print(fifa_account, status, ' ', allowed_in_sec, ' ', name, ' platform :', platform_name,
                                  ' page : ', f'https://www.mydgn.com/auctions/pick/{mydgn_id}')
                        # time.sleep(5)
                        custom_header = mydgn_session.headers.__dict__
                        custom_header.update({
                            'X-Csrf-Token': csrf_token
                        })
                        resp = mydgn_session.post(
                            f'https://www.mydgn.com/auctions/pick/{mydgn_id}', json={"platform_name": "console"},
                            headers=custom_header)
                        new_print(fifa_account, 'set buy sign : ', resp.status_code, resp.text)
                        try:
                            json_resp = resp.json()
                        except:
                            json_resp = {}
                        if resp.status_code == 200 and json_resp.get('status') != 'error':
                            target_data = {
                                'basic_card_data': card_data,
                                'mydgn_session': mydgn_session,
                                'mydgn_id': mydgn_id,
                                'resource_id': resource_id,
                                'futbin_id': futbin_id,
                                'futbin_link': futbin_link,
                                'futbin_first_price': futbin_first_price,
                                'name': name,
                                'level': level,
                                'left_time_ea_in_sec': left_time_ea_in_sec,
                                'expire_time_stamp': expire_time_stamp,
                                'end_price': end_price,
                                'avg_price': avg_price,
                                'price': price,
                                'start_price': start_price,
                                'csrf_token': csrf_token,
                            }
                            break
                        else:
                            new_print(fifa_account, 'can not set buy item , ', resp.status_code, resp.text)
            time.sleep(5)
        ws.close()
        return target_data
    else:
        try:
            # update available credit
            new_print(fifa_account, 'update available credit')
            mydgn_session = cloudscraper.create_scraper(browser={
                'browser': 'firefox',
                'platform': 'linux',
                'mobile': False
            })
            firs_page_text = mydgn_session.get('https://www.mydgn.com/').text
            token = re.search(r'name="_token" value="(.+)">', firs_page_text).group(1)
            time.sleep(2)

            login_resp = mydgn_session.post(
                'https://www.mydgn.com/login',
                json={
                    "_token": token,
                    "ses_id": "eyJjbGllbnQiOnsidHlwZSI6ImJyb3dzZXIiLCJuYW1lIjoiQ2hyb21lIiwidmVyc2lvbiI6IjExOS4wIiwiZW5naW5lIjoiQmxpbmsiLCJlbmdpbmVWZXJzaW9uIjoiIn0sIm9zIjp7Im5hbWUiOiJXaW5kb3dzIiwidmVyc2lvbiI6IjEwLjAiLCJwbGF0Zm9ybSI6Ing2NCJ9LCJkZXZpY2UiOnsidHlwZSI6ImRlc2t0b3AiLCJicmFuZCI6IiIsIm1vZGVsIjoiIiwid2lkdGgiOjE5MjAsImhlaWdodCI6MTA0MCwiY3B1Ijo0LCJyYW0iOjgsImNvb2tpZV9lbmFibGVkIjp0cnVlLCJ1c2VyX2FnZW50IjoiTW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzExOS4wLjAuMCBTYWZhcmkvNTM3LjM2IiwibGFuZ3VhZ2UiOiJlbi1HQiIsImxhbmd1YWdlcyI6WyJlbi1HQiIsImVuLVVTIiwiZW4iXX0sImJvdCI6bnVsbH0=",
                    "email": deactive_mule.user_name,
                    "password": deactive_mule.password, "remember": "on"})
            first_page = mydgn_session.get('https://www.mydgn.com/')
            current_balance = re.search('class=\"balance\">(.+)</span>', first_page.text).group(1)
            deactive_mule.refresh_from_db()
            deactive_mule.available_payment = str(current_balance)[:50]
            deactive_mule.save()
        except:
            new_print(fifa_account, 'exception in mydgn credit : ', traceback.format_exc())
        target_data = {}
        # timestamp = time.time()
        timestamp = get_db_time(timezone_=TIME_ZONE).timestamp()
        api_hash = md5(
            ('cons' + str(deactive_mule.api_user_name) + str(timestamp) + str(deactive_mule.api_secret_key)).encode()
        ).hexdigest()

        for i in range(5):
            players_list = requests.get('https://api.mydgn.com/transfers', params={
                'user': str(deactive_mule.api_user_name),
                'platform': 'cons',
                'timestamp': timestamp,
                'hash': api_hash,
                'maximumBuyOutPrice': credit,
                'minimumBuyOutPrice': discharge_lowest_target_price,

            })
            players_json_data = players_list.json()
            if players_list.json().get('code') == 200:
                mydgn_id = players_json_data['transactionID']
                resource_id = players_json_data['resourceID']
                asset_id = players_json_data['baseID']
                name = players_json_data['search_name']
                rating = players_json_data['rating']
                start_price = players_json_data['startPrice']
                end_price = players_json_data['coinAmount']
                avg_price = players_json_data['cardValue']
                if asset_id in bad_asset_ids:
                    new_print(fifa_account, 'this player has bad asset id : ', asset_id,
                              ' bad asset ids : ', bad_asset_ids)
                    continue
                target_data = {
                    'basic_card_data': players_json_data,
                    'mydgn_session': None,
                    'mydgn_id': mydgn_id,
                    'resource_id': resource_id,
                    # 'futbin_id': futbin_id,
                    # 'futbin_link': futbin_link,
                    'asset_id': asset_id,
                    'name': name,
                    'level': rating,
                    'left_time_ea_in_sec': (datetime.datetime.fromtimestamp(int(players_json_data['ea_expires_at'])) - datetime.datetime.now()).total_seconds(),
                    'expire_time_stamp': int(players_json_data['ea_expires_at']),
                    'start_price': start_price,
                    'end_price': end_price,
                    'avg_price': avg_price,
                }
                break
            elif players_json_data.get('code') == 429:
                new_print(fifa_account, 'mydgn players list : ', players_json_data)
                time.sleep(20)
            elif players_json_data.get('code') != 404:
                new_print(fifa_account, 'mydgn error : ', players_json_data)
            elif i % 10 == 0:
                new_print(fifa_account, 'mydgn bad error : ', players_json_data)

            time.sleep(5)
        return target_data


def get_card_from_buyut(parent_instance, fifa_account: FifaAccount, deactive_mule: MuleDischargeMode2, credit=0,
                        try_counter=0, bad_asset_ids=[]):
    new_print(fifa_account, 'getting card with price : ', credit, ' mule : ', deactive_mule.user_name,
              ' site : ', deactive_mule.site_name, ' ', deactive_mule.is_api)
    target_data = {}
    discharge_lowest_target_price = ConsoleBotSetting.objects.get(name='discharge_with_mode2_u7buy_lowest_target_buy_now_price').int_value
    discharge_with_mode2_highest_tax = ConsoleBotSetting.objects.get(name='discharge_with_mode2_highest_tax').int_value
    if deactive_mule.is_api is False:
        # mydgn_session = cloudscraper.create_scraper(browser={
        #     'browser': 'firefox',
        #     'platform': 'linux',
        #     'mobile': False
        # })
        # firs_page_text = mydgn_session.get('https://www.u7buyut.com/signin')
        # # print(firs_page_text.url)
        # # firs_page_text = firs_page_text.text
        # # print(firs_page_text)
        # # login_code = re.search(r"var login_code = '(.+)';", firs_page_text).group(1)
        # login_code = 2218
        # time.sleep(2)
        #
        # login_resp = mydgn_session.post(
        #     'https://www.u7buyut.com/ajax/signIn', json={
        #         'isPhoneLogin': False,
        #         'countryName': 'United States',
        #         'countryCode': 'us',
        #         'prefixAreaCode': '+1',
        #         'memberPhone': '',
        #         'memberInput': deactive_mule.user_name,
        #         'memberPassWord': deactive_mule.password,
        #         'new_user_code': '',
        #         'login_code': login_code,
        #         'remember': 1,
        #         'captcha': '',
        #     })
        # # {"icon":"Error","tips":"Incorrect account or password.","iconOut":1}
        # # {"u7referer":"1133891-37b88a796262","icon":"Success","tips":"Success","iconOut":"0"}
        # new_print(fifa_account, 'login resp : ', login_resp, ' - ', login_resp.text[:100])
        # if '"tips":"Success"' not in login_resp.text:
        #     new_print(fifa_account, 'login failed try again ', try_counter)
        #     if try_counter > 5:
        #         return target_data
        #     else:
        #         return get_card_from_buyut(
        #             parent_instance, fifa_account, deactive_mule, credit=credit, try_counter=try_counter+1)
        login_result = u7buy_login_and_save_session(fifa_account, deactive_mule)
        if login_result.get('status_bool') is False:
            new_print(fifa_account, 'login failed try again ', try_counter)
            if try_counter > 5:
                return target_data
            else:
                return get_card_from_buyut(
                    parent_instance, fifa_account, deactive_mule, credit=credit, try_counter=try_counter+1)
        else:
            mydgn_session = login_result.get('session') or requests.session()
        mydgn_session.get('https://www.u7buyut.com/sell-coins-player-trade')
        try:
            account_info = mydgn_session.get('https://www.u7buyut.com/member/player-record')
            soup = BeautifulSoup(account_info.text, "html.parser")
            available_payment = soup.find('div', class_='balanceReview').text.strip()[:100]
            address_payment = soup.find('div', class_='payAccount')
            if address_payment:
                address_payment = address_payment.text.strip()[:100]
            else:
                address_payment = ''
            a = soup.find('ul', class_='underReview').find_all('span')
            progress_payment = a[0].text.strip()[:100]
            pending_payment = a[1].text.strip()[:100]

            deactive_mule.refresh_from_db()
            deactive_mule.available_payment = available_payment
            deactive_mule.progress_payment = progress_payment
            deactive_mule.pending_payment = pending_payment
            deactive_mule.address_payment = address_payment
            deactive_mule.save()
        except:
            new_print(fifa_account, 'problem in read u7buy account data : ', traceback.format_exc())

        upp_tax_cards = []
        already_locked_cards = []
        fail_counter = 0
        for range_counter in range(5):
            if fail_counter > 10:
                new_print(fifa_account, 'fail counter more than 10 , break search')
                break
            if range_counter and range_counter % 5 == 0:
                fifa_account.refresh_from_db()
                if fifa_account.run_discharge is False:
                    return target_data
            search_payload = {'plat': 'ps4', 'range': ''}
            if 200000 < credit and range_counter < 4:
                if range_counter < 1:
                    search_payload.update({'range': '200.001-1000'})
                elif range_counter < 3:
                    search_payload.update({'range': '100.001-200'})
                else:
                    search_payload.update({'range': '50.001-100'})
            elif 100000 < credit < 200000 and range_counter < 4:
                if range_counter < 1:
                    search_payload.update({'range': '100.001-200'})
                elif range_counter < 3:
                    search_payload.update({'range': '50.001-100'})
                else:
                    search_payload.update({'range': '10.001-50'})
            elif (50000 < credit < 100000) and range_counter < 4:
                if range_counter < 2:
                    search_payload.update({'range': '50.001-100'})
                else:
                    search_payload.update({'range': '10.001-50'})
            elif (10000 < credit < 50000) and range_counter < 4:
                search_payload.update({'range': '10.001-50'})
            new_print(fifa_account, 'searching for cards , payload ', search_payload,
                      ' -- counter ', range_counter, ' -- fails ', fail_counter)
            cached_data_name = f'buyut_range_{search_payload["range"][:3]}'
            sorted_players_list = parent_instance.players_log_cache.get(cached_data_name, None)
            if sorted_players_list is None:
                new_print(fifa_account, 'cached data not found . name : ', cached_data_name)
                players_list = mydgn_session.post(
                    'https://www.u7buyut.com/ajax/playerRefresh', json=search_payload)
                if players_list.status_code == 429:
                    new_print(fifa_account, 'too many request, status code : ', players_list.status_code,
                              ' sleep 20 second')
                    parent_instance.players_log_cache.set(cached_data_name, [], timeout=5)
                    time.sleep(random.randint(15, 20))
                    continue
                sorted_players_list = sorted(players_list.json().get('insertPlayers', []),
                                             key=lambda d: int(d['buyNowPrice']), reverse=True)
                parent_instance.players_log_cache.set(cached_data_name, sorted_players_list, timeout=5)
            for card_data in sorted_players_list:
                # allowed_in_sec = card_data['allowed_in_sec']
                avg_price = int(card_data['initial_price'])
                end_price = int(card_data['buyNowPrice'])
                start_price = int(card_data['startPrice'])
                # price = card_data['price']
                # created_at_timestamp = card_data['created_at_timestamp']
                # ea_trade_id = card_data['tradeId']
                # futbin_id = card_data['futbin_id']
                resource_id = card_data['resourceId']
                asset_id = card_data['player_id']
                # futbin_link = card_data['futbin_link']
                mydgn_id = card_data['id']
                name = card_data['search_name']
                level = card_data['rating']
                version = card_data['version']
                # chemistry_style = card_data['chemistry_style']
                # contracts = card_data['contracts']
                left_time_ea_in_sec = (datetime.datetime.fromtimestamp(int(card_data['express_time'])) - datetime.datetime.now()).total_seconds()
                express_time = card_data['express_time']
                expire_time_stamp = card_data['express_time']
                # owners = card_data['owners']
                platform_name = card_data['name']
                status = card_data['status']
                # pick_block_ms = card_data['pick_block_ms']
                income_credit = card_data['income']
                if int(end_price) > int(credit):
                    new_print(fifa_account, 'credit lower than card price , credit : ', credit,
                              ' card price : ', end_price, ' card data : ', card_data)
                    continue
                if card_data in already_locked_cards:
                    new_print(fifa_account, 'this card already selected and is locked ', card_data)
                    continue
                if asset_id in bad_asset_ids:
                    new_print(fifa_account, 'this player has bad asset id : ', asset_id,
                              ' bad asset ids : ', bad_asset_ids)
                    continue
                if {'resource_id': resource_id, 'avg_price': avg_price, 'end_price': end_price} in upp_tax_cards:
                    new_print(fifa_account, 'this card in upp tax cards : ', card_data)
                    continue
                blocked_players = ConsoleSpecialNames.objects.filter(
                    Q(Q(edited_name='') | Q(edited_name=None)) & Q(Q(compare_name='') | Q(compare_name=None)),
                    player_name=name)
                if blocked_players:
                    new_print(fifa_account, 'this player has bad name and has not fixed name , ', name, blocked_players)
                    continue
                if int(end_price) < discharge_lowest_target_price:
                    new_print(fifa_account, f'buy now price less than lowest valid , ',
                              end_price, ' , ', discharge_lowest_target_price)
                    continue
                try:
                    player_card_cached_name = f'futbin_player_with_name_{str(resource_id)}'
                    futbin_data = parent_instance.players_log_cache.get(player_card_cached_name)
                    if futbin_data and futbin_data.get('local_time_stamp') > (time.time() - 300):
                        new_print(
                            fifa_account,
                            'this item was selected from futbin less than 300 seconds ago ',
                            ' , so use old data again : ', futbin_data)
                        futbin_result = futbin_data
                    else:
                        # futbin_result = parent_instance.get_price_from_futbin_and_futwiz(resource_id, wait_on_error=10)
                        futbin_result = parent_instance.get_player_data_from_futbin_with_name(
                            name,
                            level,
                            player_known_as=name,
                            rare=version,
                        )
                        if not futbin_result:
                            futbin_result = parent_instance.get_player_data_from_futbin_with_name(
                                name,
                                level,
                                player_known_as=name,
                                rare=version,
                                resource_id=resource_id,
                            )
                        if futbin_result.get('update_time_stamp'):
                            parent_instance.players_log_cache.set(
                                player_card_cached_name, futbin_result, timeout=ONE_WEEK_SECONDS
                            )
                    futbin_first_price = futbin_result.get('first_price')
                    asset_id = futbin_result.get('asset_id')
                    level = futbin_result.get('player_rating') or card_data.get('playerRating')
                except:
                    new_print(fifa_account, 'cant get data from futbin : ', traceback.format_exc()[:10000])
                    time.sleep(10)
                    continue
                if not futbin_first_price:
                    new_print(fifa_account, 'not found futbin price , futbin result : ', futbin_first_price)
                    continue
                numerator = int(futbin_first_price) * .05 + int(end_price) * .05
                current_tax = int(((numerator + avg_price - futbin_first_price) / (numerator + int(end_price) - int(avg_price))) * 100)
                if current_tax > discharge_with_mode2_highest_tax:
                    new_print(fifa_account, f'current tax higher than allowed tax 2 , ',
                              current_tax, ' , ', discharge_with_mode2_highest_tax)
                    upp_tax_cards.append({'resource_id': resource_id, 'avg_price': avg_price, 'end_price': end_price})
                    continue
                new_print(fifa_account, 'current card tax : ', current_tax)
                if end_price < credit and platform_name == 'ps4':
                    new_print(fifa_account, status, ' ', name, ' platform :', platform_name,
                              ' , page : ', f'https://www.u7buyut.com/buy-players-now.html', ' , id : ', f'{mydgn_id} ',
                              ', full data : ', card_data)
                    for _iin in [0, 1, 2, 3, 4, 5]:
                        resp = mydgn_session.post(
                            f'https://www.u7buyut.com/buy-players-now.html', json={"id": f"{mydgn_id}"})
                            # f'https://www.u7buyut.com/buy-players-now.html', json={"id": f"3"})
                        new_print(fifa_account, 'set buy sign : ', resp.status_code, resp.text[:10000])
                        if resp.status_code == 429:
                            new_print(fifa_account, 'too many request , try again in 100 sec')
                            time.sleep(random.randint(50, 100))
                            break
                        else:
                            break
                    try:
                        json_resp = resp.json()
                    except:
                        json_resp = {}
                    if resp.status_code == 200 and json_resp.get('status') == 200:
                        buy_detail = mydgn_session.get('https://www.u7buyut.com/auction-detail')
                        ut_id = re.search(r'"ut_id" type="hidden" value="(\S+)">', buy_detail.text).group(1)
                        transaction_id = re.search(r'"transaction_id" type="hidden" value="(\S+)">',
                                                   buy_detail.text).group(1)
                        token_id = re.search(r'name="_token" value="(\S+)">', buy_detail.text).group(1)
                        # try:
                        #     futbin_player_data = parent_instance.get_player_data_from_futbin_with_name(
                        #         player_name=card_data.get('playerName'),
                        #         player_rate=card_data.get('rating'),
                        #         # resource_id=card_data.get('resourceId'),
                        #         player_known_as=card_data.get('playerName'),
                        #         rare=version,
                        #     )
                        #     asset_id = futbin_player_data.get('asset_id')
                        #     level = futbin_player_data.get('player_rating') or card_data.get('playerRating')
                        # except:
                        #     new_print(fifa_account, 'cant get data from futbin , error : ', traceback.format_exc())
                        target_data = {
                            'mydgn_session': mydgn_session,
                            'mydgn_id': mydgn_id,
                            'resource_id': resource_id,
                            'asset_id': asset_id,
                            # 'futbin_id': futbin_id,
                            # 'futbin_link': futbin_link,
                            'name': name,
                            'level': level,
                            'express_time': express_time,
                            'left_time_ea_in_sec': left_time_ea_in_sec,
                            'expire_time_stamp': expire_time_stamp,
                            'end_price': end_price,
                            'avg_price': avg_price,
                            'futbin_first_price': futbin_first_price,
                            'start_price': start_price,
                            'income_credit': income_credit,
                            'ut_id': ut_id,
                            'transaction_id': transaction_id,
                            'token_id': token_id,
                            'rare': version,  # rare
                        }
                        return target_data
                    else:
                        new_print(fifa_account, 'can not set buy item , ', resp.status_code, resp.text)
                        if resp.status_code == 429:
                            fail_counter += 1
                            time.sleep(5)
                            break
                        if json_resp.get('status') == 500:
                            already_locked_cards.append(card_data)
            time.sleep(5)
    else:
        for range_counter in range(2):
            # timestamp = time.time()
            timestamp = get_db_time(timezone_=TIME_ZONE).timestamp()
            api_hash = md5(
                (str(deactive_mule.api_user_name) + 'cons' + str(credit - 1000) + str(credit) +
                 str(timestamp) + str(deactive_mule.api_secret_key)).encode()
            ).hexdigest()
            search_data = {
                'user': deactive_mule.api_user_name,
                'source': deactive_mule.user_name,
                'platform': 'cons',
                'maximumBuyOutPrice': credit - 1000,
                'minimumBuyOutPrice': max(int(discharge_lowest_target_price), 10000),
                'stock': credit,
                'timestamp': timestamp,
                'hash': api_hash,
                'request': 'transaction'
            }
            card_data = requests.post(u7buy_trade_api, data=search_data).json()
            if card_data.get('code') != 200:
                new_print(fifa_account, 'cant find card data , resp : ', card_data,
                          ' search data : ', search_data)
                time.sleep(3)
                if range_counter == 1:
                    formatted_string = ""
                    for iie_key, iie_value in search_data.items():
                        formatted_string += f"<b>{iie_key}: {iie_value}</b>\n"
                    formatted_string += f"error_code:{card_data.get('code')} "
                    parent_instance.send_message(
                        None, U7BUY_REPORT_CHANNEL_ID,
                        f'❌<b>We were unable to get a card from u7buy for this account</b>:\n\n{formatted_string}',
                        parse_mode='HTML')
            else:
                system_time = get_db_time(timezone_=TIME_ZONE)
                card_data.update({'expire_time_stamp': system_time.timestamp() + int(card_data['express_time'])})
                name = card_data.get('playerName')
                blocked_players = ConsoleSpecialNames.objects.filter(
                    Q(Q(edited_name='') | Q(edited_name=None)) & Q(Q(compare_name='') | Q(compare_name=None)),
                    player_name=name,
                    last_time__gte=timezone.localtime() - timezone.timedelta(days=2)
                )
                if blocked_players:
                    new_print(fifa_account, 'this player has bad name and has not fixed name 4 , ', name, blocked_players)
                    telegram_send_message_fifa_account(
                        fifa_account, FIFA_REPORT_TOKEN,
                        f'bad name error : \n'
                        f'cancel buy card, account {fifa_account}\nsite : {deactive_mule.site_name}\n'
                        f'player name : {card_data.get("name") or card_data.get("playerName")}\n'
                        f'cancel reason : notfound , player has bad name',
                        chat_id=ARZBAZI_REPORT_GROUP_ID,
                        message_thread_id=ARZBAZI_REPORT_TOPIC_DISCHARGE_ERROR_THREAD_MESSAGE_ID
                    )
                    cancel_buy_card(fifa_account, deactive_mule=deactive_mule, card_data=card_data,
                                    cancel_reason='notfound')
                    time.sleep(5)
                    continue
                pricing_data = requests.get('https://api.u7buyut.com/api/get_price').json()
                fee = float(pricing_data.get('cons'))
                left_time_ea_in_sec = int(card_data['express_time'])
                avg_price = int(card_data.get('initial_price'))
                end_price = int(card_data.get('buyNowPrice'))
                start_price = int(card_data.get('startPrice'))
                income_credit = ((end_price - (end_price * 0.05) - avg_price) * fee) / 1000
                resource_id = card_data.get('resourceId')
                try:
                    player_cache_name = f"futbin_player_with_name_{str(card_data.get('resourceId'))}"
                    futbin_data = parent_instance.players_log_cache.get(player_cache_name)
                    if futbin_data and futbin_data.get('local_time_stamp') > (time.time() - 600):
                        new_print(
                            fifa_account,
                            'u7buy-api, this item was selected from futbin less than 10 minute ago',
                            ' , so use old data again : ', futbin_data)
                        futbin_player_data = futbin_data
                    else:
                        futbin_player_data = parent_instance.get_player_data_from_futbin_with_name(
                            player_name=card_data.get('playerName'),
                            player_rate=card_data.get('playerRating'),
                            resource_id=resource_id,
                            # rare=int(card_data.get('version')),
                            player_known_as=card_data.get('playerName'),
                        )
                        if futbin_player_data.get('update_time_stamp'):
                            parent_instance.players_log_cache.set(
                                player_cache_name, futbin_player_data, timeout=ONE_WEEK_SECONDS)
                except:
                    new_print(fifa_account, 'error on get data from redis 2 , : ', traceback.format_exc())
                    futbin_player_data = parent_instance.get_player_data_from_futbin_with_name(
                        player_name=card_data.get('playerName'),
                        player_rate=card_data.get('playerRating'),
                        resource_id=resource_id,
                        # rare=int(card_data.get('version')),
                        player_known_as=card_data.get('playerName'),
                    )
                asset_id = futbin_player_data.get('asset_id')
                futbin_first_price = futbin_player_data.get('first_price')
                player_rating = futbin_player_data.get('player_rating') or card_data.get('playerRating')
                not_found_players = DischargeMode2.objects.filter(
                    create_time__gt=timezone.localtime() - timezone.timedelta(minutes=15),
                    player_asset_id=asset_id,
                    status='not_bought',
                ).count()
                if not_found_players >= 2:
                    new_print(fifa_account, 'not found in 15 minutes more than 2 time , cancel and buy another card')
                    cancel_buy_card(fifa_account, deactive_mule=deactive_mule, card_data=card_data,
                                    cancel_reason='notfound')
                    time.sleep(5)
                    continue
                not_found_players2 = DischargeMode2.objects.filter(
                    create_time__gt=timezone.localtime() - timezone.timedelta(minutes=15),
                    player_asset_id=asset_id,
                    status=None,
                ).count()
                if not_found_players2 >= 10:
                    new_print(fifa_account,
                              'more than unStatus account in 15 minutes for this player,',
                              ' cancel and buy another card, card data : ', card_data)
                    cancel_buy_card(fifa_account, deactive_mule=deactive_mule, card_data=card_data,
                                    cancel_reason='notfound')
                    time.sleep(5)
                    continue
                if futbin_first_price and end_price:
                    numerator = int(futbin_first_price) * .05 + int(end_price) * .05
                    current_tax = int(((numerator + avg_price - futbin_first_price) / (numerator + int(end_price) - int(avg_price))) * 100)
                else:
                    new_print(fifa_account, 'cant calculate current tax , cancel this card , ',
                              futbin_first_price, ' -- ', end_price)
                    current_tax = 100
                transaction_id = card_data.get('transactionId')
                card_data.update({'transaction_id': transaction_id})
                if current_tax > discharge_with_mode2_highest_tax:
                    new_print(fifa_account, f'current tax higher than allowed tax 4 , ',
                              current_tax, ' , ', discharge_with_mode2_highest_tax)
                    cancel_buy_card(fifa_account, deactive_mule=deactive_mule, card_data=card_data,
                                    cancel_reason='mincardvalue')
                    time.sleep(5)
                    continue
                if asset_id in bad_asset_ids:
                    new_print(fifa_account, 'this player has bad asset id 2 : ', asset_id,
                              ' bad asset ids : ', bad_asset_ids)
                    # buy_status = 'cancel'
                    cancel_buy_card(fifa_account, deactive_mule=deactive_mule, card_data=card_data,
                                    cancel_reason='mincardvalue')
                    # api_hash_2 = md5(
                    #     (str(deactive_mule.api_user_name) + str(transaction_id) + buy_status +
                    #      md5(fifa_account.user_name.encode()).hexdigest() +
                    #      str(timestamp) + str(deactive_mule.api_secret_key)).encode()
                    # ).hexdigest()
                    # requests.post(u7buy_trade_api, data={
                    #     'user': deactive_mule.api_user_name,
                    #     'transactionId': transaction_id,
                    #     'status': buy_status,
                    #     'timestamp': timestamp,
                    #     'hash': api_hash_2,
                    #     'cancelReason': 'notfound',
                    #     'emailHash': md5(fifa_account.user_name.encode()).hexdigest(),
                    #     'request': 'status',
                    # })
                    time.sleep(5)
                    continue
                new_print(fifa_account, 'u7buy api players data : ', card_data)
                target_data = {
                    'mydgn_session': None,
                    'mydgn_id': card_data.get('transactionId'),
                    'resource_id': card_data.get('resourceId'),
                    'asset_id': asset_id,
                    # 'futbin_id': futbin_id,
                    'futbin_link': futbin_player_data.get('futbin_link'),
                    'name': card_data.get('playerName'),
                    # 'level': card_data.get('playerRating'),
                    'level': player_rating,
                    # 'express_time': card_data.get('lockExpires'),
                    'left_time_ea_in_sec': left_time_ea_in_sec,
                    'expire_time_stamp': card_data.get('expire_time_stamp'),
                    'start_price': start_price,
                    'end_price': end_price,
                    'avg_price': avg_price,
                    'income_credit': income_credit,
                    'ut_id': None,
                    'transaction_id': card_data.get('transactionId'),
                    'token_id': None,
                    'contracts': card_data.get('contracts'),
                    'owners': card_data.get('owners'),
                }
                return target_data
    return target_data


def u7buy_login_and_save_session(fifa_account: FifaAccount, deactive_mule:MuleDischargeMode2, ):
    mydgn_session = cloudscraper.create_scraper(browser={
        'browser': 'firefox',
        'platform': 'linux',
        'mobile': False
    })
    if deactive_mule.session_dict:
        session_data = json.loads(deactive_mule.session_dict)
        last_headers = session_data["headers"]
        last_cookies = requests.utils.cookiejar_from_dict(session_data["cookies"])
        mydgn_session.headers.update(last_headers)
        mydgn_session.cookies = last_cookies

    firs_page_text = mydgn_session.get('https://www.u7buyut.com/signin')
    if firs_page_text.url == 'https://www.u7buyut.com/signin':
        new_print(fifa_account, 'need login again , ', deactive_mule)

        login_code = 2218
        time.sleep(2)

        login_resp = mydgn_session.post(
            'https://www.u7buyut.com/ajax/signIn', json={
                'isPhoneLogin': False,
                'countryName': 'United States',
                'countryCode': 'us',
                'prefixAreaCode': '+1',
                'memberPhone': '',
                'memberInput': deactive_mule.user_name,
                'memberPassWord': deactive_mule.password,
                'new_user_code': '',
                'login_code': login_code,
                'remember': 1,
                'captcha': '',
            })
        new_print(fifa_account, 'login resp : ', login_resp, ' - ', login_resp.text[:100])
        if '"tips":"Success"' not in login_resp.text:
            new_print(fifa_account, 'login failed try again , ', deactive_mule)
            return {'status_bool': False, 'status': 'failed', 'error': 'login_failed'}
        else:
            headers_dict = dict(mydgn_session.headers)
            cookies_dict = requests.utils.dict_from_cookiejar(mydgn_session.cookies)
            session_data = {
                "headers": headers_dict,
                "cookies": cookies_dict
            }
            deactive_mule.session_dict = json.dumps(session_data)
            deactive_mule.save(update_fields=['session_dict'])
            new_print(fifa_account, 'new login success ', deactive_mule)
    return {'status_bool': True, 'status': 'success', 'session': mydgn_session}


def get_card_from_game_currency(parent_instance, fifa_account: FifaAccount, deactive_mule: MuleDischargeMode2, credit=0,
                        try_counter=0, bad_asset_ids=[]):
    new_print(fifa_account, 'getting card with price : ', credit, ' mule : ', deactive_mule.user_name,
              ' site : ', deactive_mule.site_name)
    target_data = {}
    discharge_lowest_target_price = ConsoleBotSetting.objects.get(
        name='discharge_with_mode2_lowest_target_buy_now_price').int_value
    discharge_with_mode2_highest_tax = ConsoleBotSetting.objects.get(name='discharge_with_mode2_highest_tax').int_value
    upp_tax_cards = []
    fail_counter = 0
    # if deactive_mule.is_api:
    #     host_address = 'https://api.gamecurrency.net'
    # else:
    #     host_address = 'https://api.dev.gamecurrency.co'
    se = requests.session()
    se.headers.update({
        'Authorization': f'Bearer {deactive_mule.api_secret_key}'
    })
    host_address = 'https://fifa.gamecurrency.co'
    # players_list = se.get(f'{host_address}/v1/fifa/trades/', params={'account_credits': credit})
    players_list = requests.get(
        'https://gcapi.top/injection/api/gc-active-cards',
        headers={'accept': 'application/json'},
        params={'account_credits': credit})
    if players_list.status_code != 200:
        new_print(fifa_account, 'error on game currency : ', players_list.text)
    sorted_players_list = sorted(players_list.json(),
                                 key=lambda d: int(d['list_buy_now_price']), reverse=True)
    new_print(fifa_account, 'game currency players : ', players_list.text)
    for card_data in sorted_players_list:
        avg_price = int(card_data.get('vendor_buy_price') or card_data['player'].get('price'))
        futbin_first_price = int(card_data['player']['first_price'])
        end_price = int(card_data['list_buy_now_price'])
        start_price = int(card_data['list_start_price'])
        resource_id = card_data['player']['resource_id']
        asset_id = card_data['player']['asset_id']
        mydgn_id = card_data.get('id') or card_data['trade_id']
        origin_host = card_data.get('origin_host')
        relative_path = card_data.get('relative_path')
        name = card_data['player']['name']
        level = int(card_data['player']['rate'])
        version = int(card_data['player']['rare_id'])
        left_time_ea_in_sec = (datetime.datetime.fromtimestamp(
            int(float(card_data['player']['express_time']))) - datetime.datetime.now()).total_seconds()
        express_time = int(float(card_data['player']['express_time']))
        expire_time_stamp = int(float(card_data['player']['express_time']))
        income_credit = card_data['player']['payment_amount']
        trade_id = card_data['trade_id']

        host_address = origin_host or host_address
        if int(end_price) > int(credit):
            new_print(fifa_account, 'credit lower than card price 2, credit : ', credit,
                      ' card price : ', end_price, ' card data : ', card_data)
            continue
        if asset_id in bad_asset_ids:
            new_print(fifa_account, 'this player has bad asset id : ', asset_id,
                      ' bad asset ids : ', bad_asset_ids)
            continue
        if {'resource_id': resource_id, 'avg_price': avg_price, 'end_price': end_price} in upp_tax_cards:
            new_print(fifa_account, 'this card in upp tax cards : ', card_data)
            continue
        blocked_players = ConsoleSpecialNames.objects.filter(
            Q(Q(edited_name='') | Q(edited_name=None)) & Q(Q(compare_name='') | Q(compare_name=None)),
            player_name=name)
        if blocked_players:
            new_print(fifa_account, 'this player has bad name and has not fixed name 3, ',
                      name, ' -- ', blocked_players, ' card data : ', card_data)
            se.patch(f'{host_address}/v1/fifa/trades/{mydgn_id}/', params={'status': 'reserved'})
            time.sleep(1)
            card_data.update({'mydgn_id': mydgn_id})
            cancel_buy_card(fifa_account, deactive_mule=deactive_mule, card_data=card_data, cancel_reason='daily_ban_request')
            time.sleep(1)
            continue
        if int(end_price) < discharge_lowest_target_price:
            new_print(fifa_account, f'buy now price less than lowest valid , ',
                      end_price, ' , ', discharge_lowest_target_price)
            continue
        # futbin_first_price = avg_price
        if not futbin_first_price:
            new_print(fifa_account, 'not found futbin price , futbin result : ', futbin_first_price)
            continue
        numerator = int(futbin_first_price) * .05 + int(end_price) * .05
        current_tax = int(((numerator + avg_price - futbin_first_price) / (numerator + int(end_price) - int(avg_price))) * 100)
        # todo : uncomment bellow
        # if current_tax > discharge_with_mode2_highest_tax:
        #     new_print(fifa_account, f'current tax higher than allowed tax 3 , ',
        #               current_tax, ' , ', discharge_with_mode2_highest_tax)
        #     upp_tax_cards.append({'resource_id': resource_id, 'avg_price': avg_price, 'end_price': end_price})
        #     continue
        new_print(fifa_account, 'current card tax : ', current_tax)
        if end_price < credit:
            new_print(fifa_account, name,
                      ' , page : ', host_address, ' , id : ', f'{mydgn_id} ',
                      ', full data : ', card_data)
            resp = se.patch(f'{host_address}/v1/fifa/trades/{mydgn_id}/', params={'status': 'reserved'})
            new_print(fifa_account, 'set buy sign : ', resp.status_code, resp.text)
            if resp.status_code == 200:
                target_data = {
                    'mydgn_session': se,
                    'mydgn_id': mydgn_id,
                    'origin_host': origin_host,
                    'relative_path': relative_path,
                    'resource_id': resource_id,
                    'asset_id': asset_id,
                    'name': name,
                    'level': level,
                    'rating': level,
                    'express_time': express_time,
                    'left_time_ea_in_sec': left_time_ea_in_sec,
                    'expire_time_stamp': expire_time_stamp,
                    'start_price': start_price,
                    'end_price': end_price,
                    'avg_price': avg_price,
                    'futbin_first_price': futbin_first_price,
                    'income_credit': income_credit,
                    'rare': version,  # rare
                    'version': version,
                }
                return target_data
            else:
                new_print(fifa_account, 'can not set buy item , ', resp.status_code, resp.text)
        time.sleep(1)
    return target_data


def cancel_buy_card(fifa_account, deactive_mule: MuleDischargeMode2, card_data, cancel_reason='notfound'):
    new_print(fifa_account, 'cancel buy card , mule : ', deactive_mule, ' card data : ', card_data,
              ' cancel : ', cancel_reason)
    if deactive_mule.site_name == 'mydgn':
        if deactive_mule.is_api:
            # timestamp = time.time()
            timestamp = get_db_time(timezone_=TIME_ZONE).timestamp()
            api_hash = md5(
                ('cons' + str(deactive_mule.api_user_name) + str(timestamp) + str(
                    deactive_mule.api_secret_key)).encode()
            ).hexdigest()
            cancel_resp = requests.post('https://api.mydgn.com/status', json={
                'user': deactive_mule.api_user_name,
                'platform': 'cons',
                'timestamp': timestamp,
                'hash': api_hash,
                'transactionID': card_data.get('mydgn_id'),
                'status': 'cancel',
                'emailHash': md5(deactive_mule.user_name.encode()).hexdigest()
            })
        else:
            mydgn_id = card_data.get('mydgn_id')
            site_session = card_data.get('mydgn_session')
            cancel_resp = site_session.post(f'https://www.mydgn.com/auctions/cancel/{mydgn_id}',
                                            json={"platform_name": "console"})
        new_print(fifa_account, 'cancel response 3 : ', cancel_resp.text)

    elif deactive_mule.site_name == 'buyut':
        if deactive_mule.is_api:
            # timestamp = time.time()
            timestamp = get_db_time(timezone_=TIME_ZONE).timestamp()
            buy_status = 'cancel'
            transaction_id = card_data.get('transaction_id')
            api_hash_2 = md5(
                (str(deactive_mule.api_user_name) + str(transaction_id) + buy_status +
                 md5(fifa_account.user_name.encode()).hexdigest() +
                 str(timestamp) + str(deactive_mule.api_secret_key)).encode()
            ).hexdigest()
            cancel_resp = requests.post(u7buy_trade_api, data={
                'user': deactive_mule.api_user_name,
                'transactionId': transaction_id,
                'status': buy_status,
                'timestamp': timestamp,
                'hash': api_hash_2,
                'cancelReason': cancel_reason,
                'emailHash': md5(fifa_account.user_name.encode()).hexdigest(),
                'request': 'status',
            })
            time.sleep(5)
        else:
            site_session = card_data.get('mydgn_session')
            cancel_resp = site_session.post('https://www.u7buyut.com/buy-players-cancel.html', json={
                '_token': card_data.get('token_id'),
                'version_72': '72',
                'ut_id': card_data.get('ut_id'),
                'transaction_id': card_data.get('transaction_id')
            })
        new_print(fifa_account, 'cancel response 2 : ', cancel_resp.text)
    elif deactive_mule.site_name == 'game_currency':
        host_address = card_data.get('origin_host') or 'https://fifa.gamecurrency.co'
        trade_id = card_data.get('mydgn_id') or card_data.get('trade_id')
        if cancel_reason == 'notfound':
            cancel_reason = 'market_empty'
        cancel_resp = requests.patch(
            f'{host_address}/v1/fifa/trades/{trade_id}/',
            params={'status': 'canceled', 'cancellation_reason': cancel_reason},
            headers={'Authorization': f'Bearer {deactive_mule.api_secret_key}'}
        )
        new_print(fifa_account, 'cancel response 2 : ', cancel_resp.text)
    telegram_send_message_fifa_account(
        fifa_account, FIFA_REPORT_TOKEN,
        f'cancel buy card, account {fifa_account}\nsite : {deactive_mule.site_name}\n'
        f'player name : {card_data.get("name") or card_data.get("playerName")}\n'
        f'cancel reason : {cancel_reason}',
        chat_id=ARZBAZI_REPORT_GROUP_ID,
        message_thread_id=ARZBAZI_REPORT_TOPIC_DISCHARGE_ERROR_THREAD_MESSAGE_ID
    )


def save_sold_items(fifa_account: FifaAccount, trade_pile_json: dict):
    # too many database usage and not need anymore
    return {'status_bool': True, 'status': 'success', 'created': False}
    new_print(fifa_account, 'save sold items')
    for item in trade_pile_json.get('auctionInfo', []):
        if item.get('tradeState') == 'closed':
            try:
                sold_item = AccountSoldItem.objects.get(
                    fifa_account=fifa_account,
                    item_id=deep_get(item, 'itemData.id', 0),
                    is_sold=False
                )
                sold_item.sell_price = item.get('currentBid') or 0
                sold_item.is_sold = True
                sold_item.sale_time = timezone.localtime()
                sold_item.save()
                time.sleep(1)
            except:
                new_print(fifa_account, 'exception in save sold items : ', traceback.format_exc())


def save_quick_sold_item(fifa_account: FifaAccount, item_id, discard_value=0):
    # too many database usage and not need anymore
    return {'status_bool': True, 'status': 'success', 'created': False}
    try:
        sold_item = AccountSoldItem.objects.get(
            fifa_account=fifa_account,
            item_id=item_id,
            is_sold=False
        )
        sold_item.is_sold = True
        sold_item.sale_time = timezone.localtime()
        sold_item.is_quick_sell = True
        if discard_value:
            sold_item.discard_value = int(discard_value)
        sold_item.save()
        time.sleep(1)
    except:
        new_print(fifa_account, 'exception in save quick sold items : ', traceback.format_exc())


def save_selling_items(fifa_account: FifaAccount, item_id, item_type, buy_price, rating, rare, asset_id, discard_value):
    # too many database usage and not need anymore
    return {'status_bool': True, 'status': 'success', 'created': False}
    selling_item, created = AccountSoldItem.objects.get_or_create(
        fifa_account=fifa_account,
        item_id=item_id,
        is_sold=False,
    )
    if created:
        selling_item.item_type = item_type
        selling_item.buy_price = buy_price
        selling_item.rating = rating
        selling_item.rare = rare
        selling_item.asset_id = asset_id
        selling_item.discard_value = discard_value
        selling_item.save()
        return {'status_bool': True, 'status': 'success', 'created': True}
    return {'status_bool': True, 'status': 'success', 'created': False}


def get_chemistryProfilesVersion(fifa_account, se: Session, header):
    resp = se.get(f'{fifa_23_address}/chemistry/profiles', headers=header)
    try:
        profile_version = resp.json().get('version')
        if profile_version:
            return {'status_bool': True, 'status': 'success', 'version': profile_version}
        else:
            new_print(fifa_account, ' get chemistryProfilesVersion resp : ', resp.text)
            return {'status_bool': False, 'status': 'failed', 'reason': 'chemistry value none'}
    except:
        return {'status_bool': False, 'status': 'failed', 'reason': traceback.format_exc()}


def convert_club_players_to_solvation_format(club_players):
    final_list = []
    final_list.append(["Name", "Rating", "Rarity", "PreferredPosition", 'RarityGroup',
                       "Nation", "League", "Team", "LastSalePrice",
                       "DiscardValue", "Untradeable", "Loans", "DefinitionId", "IsDuplicate", "IsInActive11",
                       "AlternatePositions", "ExternalPrice", "IsExists", 'AssetId', 'ResourceId', 'FutbinId',
                       'RawTeamId'])
    for item_1 in club_players:
        final_list.append([
            item_1.get('assetId'),
            int(item_1.get('rating')),
            str(item_1.get('rareflag')),
            item_1.get('preferredPosition'),
            ','.join(str(xx) for xx in (item_1.get('groups') or [])),
            str(item_1.get('nation')),
            str(item_1.get('leagueId')),
            str(item_1.get('teamid')),
            item_1.get('lastSalePrice') or 0,
            item_1.get('discardValue') or 0,
            item_1.get('untradeable') or False,
            item_1.get('loans') or False,
            item_1.get('id'),
            False,
            False,
            ','.join(item_1.get('possiblePositions')),
            item_1.get('lastSalePrice') or item_1.get('discardValue') or item_1.get('marketDataMinPrice') or 100,
            1,
            item_1.get('assetId'),
            item_1.get('resourceId'),
            item_1.get('futbinId'),
            str(item_1.get('teamid')),
        ])
    return final_list


# becareful , this function and convert_club_players_to_solvation_format must have same title
def convert_player_cards_to_solvation_format(player_cards):
    final_list = []
    final_list.append(["Name", "Rating", "Rarity", "PreferredPosition", 'RarityGroup',
                       "Nation", "League", "Team", "LastSalePrice",
                       "DiscardValue", "Untradeable", "Loans", "DefinitionId", "IsDuplicate", "IsInActive11",
                       "AlternatePositions", "ExternalPrice", "IsExists"])
    for item_1 in player_cards:
        final_list.append([
            item_1.asset_id,
            int(item_1.rating),
            str(item_1.rare),
            item_1.position,
            item_1.groups,
            str(item_1.nation),
            str(item_1.league),
            str(item_1.team),
            item_1.price or 0,
            0,
            False,
            False,
            0,
            False,
            False,
            item_1.position +','+ item_1.alternate_positions if item_1.alternate_positions else item_1.position,
            item_1.price,
            0,
        ])
    return final_list


def convert_players_to_solvation_format(players_data):
    final_list = []
    final_list.append(["Name", "Rating", "Rarity", "PreferredPosition", 'RarityGroup',
                       "Nation", "League", "Team", "LastSalePrice",
                       "DiscardValue", "Untradeable", "Loans", "DefinitionId", "IsDuplicate", "IsInActive11",
                       "AlternatePositions", "ExternalPrice", "IsExists", 'AssetId', 'ResourceId', 'FutbinId',
                       'RawTeamId'])
    for item_1 in players_data:
        final_list.append([
            item_1.get('asset_id'),
            int(item_1.get('rating')),
            str(item_1.get('rare')),
            item_1.get('position'),
            item_1.get('groups'),
            str(item_1.get('nation')),
            str(item_1.get('league')),
            str(item_1.get('team')),
            item_1.get('price') or 0,
            item_1.get('price') or 0,
            False,
            False,
            0,
            False,
            False,
            item_1.get('alter_position'),
            item_1.get('price') or 100,
            0,
            item_1.get('asset_id'),
            item_1.get('resource_id'),
            item_1.get('futbinId'),
            str(item_1.get('team')),
        ])
    return final_list


def get_newest_solvations_players(parent_instance, sbc_type_obj: SBCType, solvation_model: SBCSolvationModel = None):
    fifa_account = parent_instance.fifa_account
    all_players_data = []
    best_solvations = 0
    counter = 0
    if solvation_model and solvation_model.buy_player_links:
        new_print(fifa_account, f'finding solvation from links : ', solvation_model.buy_player_links)
        cant_buy_players = [json.loads(eei.decode('utf-8')) for eei in print_cache2.lrange('cant_buy_players', start=0, end=-1)]
        last_hour_ago = timezone.localtime() - timezone.timedelta(hours=1)
        cant_buy_assets = [str(iie['asset_id']) for iie in cant_buy_players if timezone.datetime.fromisoformat(iie['create_time']) > last_hour_ago]
        links = eval(solvation_model.buy_player_links)
        cant_buy_players_2 = []
        players_elemenst = []
        for link_with_page in links:
            # new_print(fifa_account, 'getting link for players ', link_with_page)
            link_result = parent_instance.use_cloud_scraper(link_with_page)
            time.sleep(5)
            soup = BeautifulSoup(link_result.content, 'html.parser')
            players_table = soup.find(class_='players-table')
            if players_table:
                for row_item in players_table.find_all(class_='player-row'):
                    players_elemenst.append(row_item)
            else:
                new_print(fifa_account, 'can not find players table , ', link_result.status_code,
                          ' , content ', link_result.text[:10000])
                time.sleep(random.randint(10, 20))
        for row in players_elemenst:
            futbin_link = row.find('a')['href']
            futbin_image = row.find('img')['src']
            asset_id = re.search('players/(\d+).png', (futbin_image or ''))
            if asset_id:
                asset_id = asset_id.group(1)
            else:
                continue
            player_name = row.find(class_='table-player-name').text
            sub_data = row.find(class_='table-player-sub-info')
            nation_id = re.search(r'nation/(\d+).png', urllib.parse.unquote(
                sub_data.find(class_='table-player-nation').find('img')['src'])).group(1)
            league_id = re.search(r'league/dark/(\d+).png', urllib.parse.unquote(
                sub_data.find(class_='table-player-league').find('img')['src'])).group(1)
            club_id = re.search(r'clubs/dark/(\d+).png', urllib.parse.unquote(
                sub_data.find(class_='table-player-club').find('img')['src'])).group(1)
            rating_box = row.find(class_='table-rating')
            rating = rating_box.text.replace('\n', '')
            rare = re.search(r'tiny/(\d+)_', urllib.parse.unquote(rating_box.find('img')['src'])).group(1)
            price_element = row.find(class_=["platform-ps-only", "table-price"])
            player_pos = row.find(class_='table-pos').contents
            player_position = ''
            if len(player_pos) > 1:
                player_position = player_pos[1].text
            alter_positions = player_position
            if len(player_pos) > 3:
                alter_positions = alter_positions + ',' + player_pos[3].text.replace(' ', '')
            futbin_id = re.search('player/(\d+)/', futbin_link)
            if futbin_id:
                futbin_id = futbin_id.group(1)
            else:
                futbin_id = None
            price_number = 0
            if price_element:
                price_text = price_element.find('div').text
                price_number = price_text.replace('K', '').replace('M', '')
                if 'M' in price_text:
                    price_number = float(price_number) * 1000000
                elif 'K' in price_text:
                    price_number = float(price_number) * 1000
                else:
                    price_number = float(price_number)
            if str(asset_id) in cant_buy_assets:
                cant_buy_players_2.append({'asset_id': asset_id, 'futbin_link': futbin_link, 'price': price_number})
                continue
            all_players_data.append({
                'asset_id': int(asset_id),
                'assetId': int(asset_id),
                'resource_id': int(asset_id),  # resource id not fix
                'resourceId': int(asset_id),  # resource id not fix
                'rating': rating,
                'rare': int(rare),
                'groups': '',
                'futbin_link': futbin_link,
                'futbin_id': futbin_id,
                'futbinId': futbin_id,
                'position': player_position,
                'alter_position': alter_positions,
                'futbin_image': futbin_image,
                'player_name': player_name,
                'nation': int(nation_id),
                'league': int(league_id),
                'club': int(club_id),
                'team': int(club_id),
                'price': int(price_number),
            })
        new_print(fifa_account, 'cant buy this players : ', cant_buy_players_2)
        return all_players_data
    sbc_link_resp = parent_instance.use_cloud_scraper(f'{futbin_address}/squad-building-challenges/ALL/{sbc_type_obj.sbc_number}/a')
    solvations_id = re.findall('href="/25/squad/([^"]+)/sbc" ', sbc_link_resp.text)
    new_print(fifa_account, f'finding {len(solvations_id)} solvation')
    while best_solvations < 3 and counter < 10:
        time.sleep(2)
        sbc_solve_link = f'{futbin_address}/squad/{solvations_id[counter]}/sbc'
        counter += 1
        new_print(fifa_account, 'getting data of ', sbc_solve_link)
        # soup_handler_2 = BeautifulSoup(scraper.get(sbc_solve_link).text, "html.parser")
        resp = parent_instance.use_cloud_scraper(sbc_solve_link).text
        react_data = re.search(r'data-react-data="">(.+)</script>', resp).group(1)
        react_data = json.loads(str(react_data.replace('&quot;', '"')))
        bad_players = 0
        targets_list = []
        fifa_player_position = -1
        squad_data = react_data.get('squadData').get('squad')
        players_list = []
        selected_formation_name = react_data.get('sbcChallengeRequirementData').get('formation').get('displayName')
        for iii in parent_instance.squad_positions_in_futbin[selected_formation_name]:
            data_position_idx = None
            for data_position, player_data in enumerate(squad_data):
                if data_position == 0 or data_position % 2 == 0:
                    if player_data['value'] == iii:
                        data_position_idx = data_position + 1
                        break
            fifa_player_position += 1
            if not data_position_idx:
                continue
            player_data = squad_data[data_position_idx]
            player_asset_id = int(re.search(
                r'img/players/(.\d+)\.png',
                str(urllib.parse.unquote(player_data.get('playerImage').get('fixed').get('url').get('image1x')))
            ).group(1))
            player_futbin_id = player_data.get('id')
            player_club = player_data.get('clubId').get('value')
            player_club_name = player_data.get('chemistryCard').get('chemData').get('clubName')
            player_rating = player_data.get('statsCard').get('rating')
            player_position = player_data.get('position').get('value')
            alter_positions = [iii['value'] for iii in player_data.get('possiblePositions')]
            player_rare_type = player_data.get('rareType')
            league_id = player_data.get('leagueId').get('value')
            nation_id = player_data.get('nationId').get('value')
            player_price = deep_get(player_data, 'price.ps.price', 200)
            player_data = {
                'asset_id': player_asset_id,
                'resource_id': player_asset_id,  # resource id not fix
                'rating': player_rating,
                'rare': player_rare_type,
                'futbin_link': f'{futbin_address}/player/{player_futbin_id}/a',
                'futbin_id': player_futbin_id,
                'position': player_position,
                'alter_position': ','.join(alter_positions),
                'nation': nation_id,
                'league': league_id,
                'club': player_club,
                'team': player_club,
                'price': player_price
            }
            players_list.append(player_data)
            time.sleep(1)
        all_players_data = all_players_data + players_list
        best_solvations += 1
    return all_players_data


def convert_futbin_time(futbin_time):
    if futbin_time == 'Never':
        return 0
    if futbin_time.find('secs') == -1:
        futbin_updated_time = 0
        if futbin_time.find('mins') != -1 or futbin_time.find('min') != -1:
            updated_time_min = futbin_time.split()
            futbin_updated_time = timezone.localtime() - timezone.timedelta(minutes=int(updated_time_min[0]))
            futbin_updated_time = futbin_updated_time.timestamp()
        elif futbin_time.find('hours') != -1 or futbin_time.find('hour') != -1:
            updated_time_hour = futbin_time.split()
            futbin_updated_time = timezone.localtime() - timezone.timedelta(hours=int(updated_time_hour[0]))
            futbin_updated_time = futbin_updated_time.timestamp()
        return futbin_updated_time
    else:
        return get_db_time(timezone_=TIME_ZONE).timestamp()


def get_trade_access_from_usermassinfo(se):
    mass_info = se.get(f'{fifa_23_address}/usermassinfo')
    mass_info_json = mass_info.json()
    trade_access = deep_get(mass_info_json, 'userInfo.feature.trade', None)
    return trade_access
