import ast
import json
import os
import random
import re
import time
import traceback
import urllib
from datetime import datetime, timedelta

import cloudscraper
import requests
import telepot
from bs4 import BeautifulSoup
from django.db import close_old_connections
from django.db.models import Count, F, Subquery, OuterRef, IntegerField, Value
from django.db.models.functions import Coalesce
from django.utils import timezone
from django.utils.timezone import get_current_timezone
from selenium.webdriver.common.action_chains import ActionChains

from accounts.models import PlayerCard, FifaProxy, FifaAccount, FifaAccountSearch, MuleAccounts, SniperPlayerCard, \
    ConsoleBotSetting, TelegramMessage, AccountLoginLog
from futplus.celery_conf import app
from futplus.settings import BASE_DIR
from sbc import FIFA_REPORT_TOKEN, ARZBAZI_REPORT_GROUP_ID, ARZBAZI_REPORT_TOPIC_GENERAL_THREAD_MESSAGE_ID
from sbc.login_to_ea_with_selenium import login_to_account, wait_for_element
from sbc.public_methods import get_next_price_grade, get_previous_price_grade, get_round_top_price, most_common, \
    new_print, force_get, put_item_for_sale, delete_sold_items, get_credit_web, ThreadWithReturnValue, \
    convert_futbin_time, user_agent, telegram_send_photo
from sniper.models import SniperAccount, SniperTradeItemLog
from trade.models import TradeLog
from utils.ea_settings import fifa_host, fifa_23_address, fut_web_number, futbin_address, accounts_ea_auth_url
from utils.login_to_ea_with_requests import LoginWithRequest
from utils.tools import select_platform

# TOKEN = '5069069452:AAGamQnbejLF-jJTfswdLYHGIyPNwf0vah0'
# bot = telepot.Bot(TOKEN)
bot = telepot.Bot(FIFA_REPORT_TOKEN)
third_account = 0


class SniperRunner:

    def __init__(self, sender: SniperAccount, receiver: SniperAccount, catcher: SniperAccount):
        self.sender = sender
        self.receiver = receiver
        self.catcher = catcher
        self.reverse_catcher = False
        self.platform_key = select_platform['ps']['platform_key']
        self.server_key = select_platform['ps']['server_key']
        self.main_dic = {'found': 0, 'first_bid': 0, 'fail_number': 0}
        self.main_dic['pin_enevts_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',
            'Host': fifa_host,
            'x-ea-game-id': fut_web_number, 'x-ea-game-id-type': 'easku',
            'x-ea-taxv': '1.1'
        }
        self.main_dic['pin_enevts_option_header'] = {
            'Access-Control-Request-Headers': 'content-type,x-ea-game-id,x-ea-game-id-type,x-ea-taxv',
            'Access-Control-Request-Method': 'POST',
            'Origin': 'https://www.ea.com',
            'Referer': 'https://www.ea.com/',
            'User-Agent': user_agent
        }
        self.main_dic['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': 'GET',
                                           'Origin': 'https://www.ea.com',
                                           'Referer': 'https://www.ea.com/',
                                           'User-Agent': user_agent
                                           }

        self.file_path = os.path.dirname(os.path.abspath(__file__))
        # fake_trade_id = TradeLog.objects.filter(
        #     create_time__gt=timezone.localtime() - timezone.timedelta(days=7)
        # ).exclude(
        #     trade_id__in=['', None],
        # ).last()
        # if fake_trade_id:
        #     self.fake_trade_id = fake_trade_id.trade_id
        # else:
        #     self.fake_trade_id = 466355881582
        self.fake_trade_id = 550051512655
        self.fifa_account = self.receiver.fifa_account
        self.username = self.receiver.fifa_account.user_name
        self.running_platform = 'web'
        self.account_high_search_count = ConsoleBotSetting.objects.get(name='account_high_search_count').int_value
        self.last_time_get_new_sid = timezone.localtime()
        self.danger_get_new_sid_counter = 0


    def get_ea_options_header(self, method='GET'):
        return {
            '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': method,
            'Origin': 'https://www.ea.com',
            'Referer': 'https://www.ea.com/',
            'User-Agent': user_agent
        }

    def use_cloud_scraper(self, link, proxy_ip, proxy_port, proxy_user, proxy_pass):
        new_print(self.fifa_account, 'link = ', link)
        counter = 0
        while True:
            new_print(self.fifa_account, 'counter = ', counter, 'proxie = ', proxy_ip,
                      proxy_port)
            counter += 1
            scraper = cloudscraper.create_scraper(browser={
                'browser': 'firefox',
                'platform': 'linux',
                'mobile': False
            })
            if str(proxy_ip):
                proxies = {
                    'http': f'http://{proxy_user}:{proxy_pass}@{proxy_ip}:{proxy_port}',
                    'https': f'http://{proxy_user}:{proxy_pass}@{proxy_ip}:{proxy_port}'
                }
                resp = scraper.get(link, proxies=proxies)
            else:
                resp = scraper.get(link)
            if resp.text.find('Why do I have to complete a CAPTCHA?') == -1:
                break
            new_print(self.fifa_account, resp.text[:100])
            time.sleep(2)
            if counter % 10 == 0:
                self.send_message(bot, 123, 'cant get price from futbin for 10 try. account = %s. ip = %s' % (
                    self.username, proxy_ip))
        return resp

    # def get_price_from_futbin_and_futwiz(self, se, proxy_ip, proxy_port, proxy_user, proxy_pass, player_asset_id):
    #     resp = self.use_cloud_scraper('https://www.futbin.com/24/playerPrices?player=%s' % player_asset_id, proxy_ip,
    #                                   proxy_port, proxy_user, proxy_pass)
    #     try:
    #         # json_resp = resp.json()
    #         json_resp = json.loads(resp)
    #     except:
    #         # todo : set proxy expire . sbcsolver instance
    #         new_print(self.fifa_account, 'error 80 : ', traceback.format_exc())
    #         time.sleep(1000)
    #
    #     futbin_prices = json_resp[str(player_asset_id)]['prices']['ps']
    #     futbin_all_prices_list = []
    #     first_price = 0
    #     futbin_min_price = futbin_max_price = 0
    #     try:
    #         futbin_min_price = futbin_prices.get('MinPrice', "0")
    #         futbin_min_price = int(futbin_min_price.replace(',', ''))
    #         futbin_max_price = futbin_prices.get('MaxPrice', "0")
    #         futbin_max_price = int(futbin_max_price.replace(',', ''))
    #     except:
    #         pass
    #
    #     if futbin_prices.get('LCPrice', "0") != "0":
    #         first_price = futbin_prices.get('LCPrice', "0")
    #         futbin_all_prices_list.append(futbin_prices.get('LCPrice', "0"))
    #     if futbin_prices.get('LCPrice2', "0") != "0":
    #         futbin_all_prices_list.append(futbin_prices.get('LCPrice2', "0"))
    #     if futbin_prices.get('LCPrice3', "0") != "0":
    #         futbin_all_prices_list.append(futbin_prices.get('LCPrice3', "0"))
    #     if futbin_prices.get('LCPrice4', "0") != "0":
    #         futbin_all_prices_list.append(futbin_prices.get('LCPrice4', "0"))
    #     if futbin_prices.get('LCPrice5', "0") != "0":
    #         futbin_all_prices_list.append(futbin_prices.get('LCPrice5', "0"))
    #     new_print(self.fifa_account, 'futbin_all_prices_list = ', futbin_all_prices_list)
    #     if len(futbin_all_prices_list) == 0:
    #         futbin_all_prices_list = ["0"]
    #     futbin_player_price = most_common(futbin_all_prices_list)
    #     # futbin_player_price = json_resp[str(player_asset_id)]['prices']['ps']['LCPrice']
    #     futbin_price_update_time = json_resp[str(player_asset_id)]['prices']['ps']['updated']
    #     new_print(self.fifa_account, 'futbin player price = ', futbin_player_price, futbin_price_update_time)
    #
    #     # try:
    #     #     futwiz_base_url = 'https://www.futwiz.com'
    #     #     resp = se.get(futwiz_base_url + '/en/player/history/%s' % player_asset_id)
    #     #     # soup = BeautifulSoup(resp.content, "html.parser")
    #     #     # dom = etree.HTML(str(soup))
    #     #     dom = html.fromstring(resp.text)
    #     #     a_elem_href = (dom.xpath("//div[@class = 'pull-left mr-10 text-center mb-10']/a")[0]).attrib['href']
    #     #     # print a_elem_href
    #     #     resp = se.get(futwiz_base_url + a_elem_href)
    #     #     # soup = BeautifulSoup(resp.content, "html.parser")
    #     #     # dom = etree.HTML(str(soup))
    #     #     dom = html.fromstring(resp.text)
    #     #     ps_price_elem = (dom.xpath("//div[@class = 'playerprofile-price text-center']")[1]).text
    #     #     futwiz_ps_price_elem = ''.join(ps_price_elem.split())
    #     #     page = resp.content
    #     #     help_elem = page.find('class="hidemob"') + 1
    #     #     help_elem = page.find('class="hidemob"', help_elem)
    #     #     tag = '</span>'
    #     #     begin = page.find(tag, help_elem) + len(tag)
    #     #     end = page.find('<hr', begin)
    #     #     futwiz_ps_price_update_time_elem = page[begin:end]
    #     #     # ps_price_update_time_elem = (dom.xpath("//div[@class = 'playerprofile-prices-ps text-center']")[0]).text
    #     #     futwiz_ps_price_update_time_elem = ' '.join(futwiz_ps_price_update_time_elem.split())
    #     #     new_print(self.fifa_account, 'futwiz player price = ', futwiz_ps_price_elem,
    #     #               futwiz_ps_price_update_time_elem)
    #     # except:
    #     #     new_print(self.fifa_account, traceback.format_exc())
    #
    #     price = futbin_player_price
    #     # if (futwiz_ps_price_update_time_elem.find('min') != -1) and (
    #     #         futbin_price_update_time.find('hour') != -1 or futbin_price_update_time.find('week') != -1 or futbin_price_update_time.find('Never') != -1):
    #     #     price = futwiz_ps_price_elem
    #     # elif (futwiz_ps_price_update_time_elem.find('hrs') != -1) and (futbin_price_update_time.find('week') != -1 or futbin_price_update_time.find('Never') != -1):
    #     #     price = futwiz_ps_price_elem
    #     price = int(price.replace(',', ''))
    #     first_price = int(str(first_price).replace(',', ''))
    #     return price, futbin_price_update_time, first_price, futbin_min_price, futbin_max_price


    def get_price_from_futbin_and_futwiz(self, player_asset_id, print_log=True, wait_on_error=1000, page_source=None):
        """

        @param player_asset_id: player futbin id .
        @type player_asset_id:
        @param print_log:
        @type print_log:
        @return:
        @rtype:
        """
        if page_source:
            resp = page_source
        else:
            resp = self.use_cloud_scraper(
                f'{futbin_address}/player/{player_asset_id}/a',
                self.sender_proxy_ip, self.sender_proxy_port, self.sender_proxy_user, self.sender_proxy_password
            ).text
            if resp.find('Your client does not have permission') != -1:
                new_print(self.fifa_account, 'error 40 : ', traceback.format_exc(), ' ,   futbin result : ', resp)
                if resp.find('Your client does not have permission') != -1:
                    text = 'proxy %s:%s is dead for futbin' % (self.main_dic.get('proxy_ip'), self.main_dic.get('proxy_port'))
                    self.send_message(bot, 'critical', text)

                    proxy = FifaProxy.objects.filter(ip_address=self.main_dic['proxy_ip'],
                                                     port=self.main_dic['proxy_port']).first()
                    if proxy:
                        proxy.delete()

                    self.handle_end_bot(without_update_time=1)
                    return {}
                if wait_on_error:
                    time.sleep(wait_on_error)
        soup = BeautifulSoup(resp, "html.parser")
        card_price_info = None
        for iie in soup.find_all(class_='price-box'):
            # if 'price-box' in iie['class'] and 'player-price-not-ps' in iie['class'] and 'hidden' not in iie['class']:
            if ('price-box' in iie['class'] and
                    # 'player-price-not-ps' in iie['class'] and
                    'platform-ps-only' in iie['class'] and
                    'price-box-original-player' in iie['class']):
                card_price_info = iie
                break
        futbin_all_prices_list = []
        futbin_min_price = futbin_max_price = 0
        try:
            pr_price = card_price_info.find(class_='price-pr').text.split(' ')
            futbin_min_price = pr_price[1]
            futbin_min_price = int(futbin_min_price.replace(',', ''))
            futbin_max_price = pr_price[3]
            futbin_max_price = int(futbin_max_price.replace(',', ''))
        except:
            pass
        first_price = card_price_info.find(class_='lowest-price-1').text
        for itii in card_price_info.findAll(class_='lowest-price'):
            futbin_all_prices_list.append(itii.text.replace(',', ''))
        if print_log:
            new_print(self.fifa_account, 'futbin_all_prices_list = ', futbin_all_prices_list)
        if len(futbin_all_prices_list) == 0:
            futbin_all_prices_list = ["0"]
        futbin_player_price = most_common(futbin_all_prices_list)
        # futbin_player_price = json_resp[str(player_asset_id)]['prices']['ps']['LCPrice']
        futbin_price_update_time = card_price_info.find(
            class_='prices-updated'
        ).text.replace('Price Updated: ', '')
        if print_log:
            new_print(self.fifa_account, 'futbin player price , min : ', futbin_min_price,
                      ' current buy now : ', futbin_player_price, ' update time : ', futbin_price_update_time)
        console_display_name = soup.find(class_='playercard-25-name text-ellipsis').text
        if futbin_player_price:
            price = futbin_player_price
            price = int(str(price).replace(',', ''))
            first_price = int(str(first_price).replace(',', ''))
            return {'price': price, 'update_time': futbin_price_update_time, 'first_price': first_price,
                    'futbin_price_list': futbin_all_prices_list,
                    'futbin_min_price': futbin_min_price, 'futbin_max_price': futbin_max_price,
                    'update_time_stamp': convert_futbin_time(futbin_price_update_time),
                    'local_time_stamp': time.time(),
                    'asset_id': 0, 'display_name': console_display_name}
        else:
            return {}

    def get_data_from_furbin_with_target_information(self, futbin_id, rare_type=None):
        # todo : after futbin update , this method need to update
        bad_player = False
        resp2 = self.use_cloud_scraper(
            f'{futbin_address}/player/{futbin_id}/a',
            self.sender_proxy_ip, self.sender_proxy_port, self.sender_proxy_user, self.sender_proxy_password
        ).text
        soup = BeautifulSoup(resp2, "html.parser")
        player_asset_id = None
        meta_tag = soup.find("meta", {"property": "og:image"})
        if meta_tag and meta_tag.get("content"):
            content_url = meta_tag["content"]
            match = re.search(r"/players/(\d+)\.png", content_url)
            if match:
                player_asset_id = match.group(1)
        player_card_wrapper = soup.find(class_='player-card-wrapper')
        player_futbin_id = player_card_wrapper['data-id']
        player_rating = soup.find(class_='playercard-25-rating').text
        display_name = player_card_wrapper.find('div', attrs={'title': True})['title']
        player_wrapper_image = player_card_wrapper.find('img', class_='playercard-25-base-img')
        if not player_wrapper_image:
            player_wrapper_image = player_card_wrapper.find('img', class_='playercard-25-special-img')
        try:
            player_image_url = player_card_wrapper.find('img')['src']
            current_player_rare = int(re.search(
                'hd/(\d+)_', str(urllib.parse.unquote(player_image_url))
            ).group(1))
        except:
            current_player_rare = 2
        player_resource_id = re.search(r'/players/(.+)\.png',
                                       urllib.parse.unquote(
                                           player_wrapper_image['src']))
        if player_resource_id:
            player_resource_id = player_resource_id.group(1)
            player_resource_id = ''.join([ii for ii in player_resource_id if ii.isdigit()])
        else:
            player_resource_id = 0
        # player_versions = soup.find(class_="player-versions")
        # player_rare = re.search('data-rare-type=\"(.+)\" ', resp2).group(1)
        player_rare = int(re.search(
            'hd/(\d+)_', str(urllib.parse.unquote(player_card_wrapper.find('img')['src']))
        ).group(1))
        # data_baseid = re.search('data-baseid="(\d+)"', resp2)
        # if data_baseid:
        #     target_asset_id = data_baseid.group(1)
        new_print(self.fifa_account, 'target futbin data , futbin_id : ', futbin_id,
                  'player data : rate = ', player_rating, ' rare = ', player_rare,
                  ' asset id = ', player_asset_id)
        card_info = None
        for iie in soup.find_all(class_='price-box'):
            # if 'price-box' in iie['class'] and 'player-price-not-ps' in iie['class'] and 'hidden' not in iie['class']:
            if ('price-box' in iie['class'] and
                    # 'player-price-not-ps' in iie['class'] and
                    'platform-ps-only' in iie['class'] and
                    'price-box-original-player' in iie['class']):
                card_info = iie
                break
        if not card_info.find(class_='lowest-price-1'):
            new_print(self.fifa_account, 'bad player , has not price')
            bad_player = True
        if not bad_player:
            try:
                current_version = re.search(
                    r'hd/([^.]+)\.png', str(urllib.parse.unquote(player_card_wrapper.find('img')['src']))
                ).group(1)
                # pversions = player_versions.find(
                pversions = soup.find(
                    class_='player-header-card-section'
                ).find_all(
                    lambda tag: 'player-card-wrapper' in tag.get('class', []) and 'hidden' in tag.get('class', [])
                )
                if pversions:
                    # gold_cards_info = []
                    other_rarities = []
                    for pversion in pversions:
                        card_version = re.search(
                            r'hd/([^.]+)\.png', str(urllib.parse.unquote(pversion.find('img')['src']))
                        ).group(1)
                        # a_elem = pversion.find('a')
                        # player_image_url = pversion.find('img')['src']
                        other_rarities.append(card_version)
                        # player_rare_tmp = int(re.search(
                        #     'hd/(\d+)_', str(urllib.parse.unquote(player_image_url))
                        # ).group(1))
                        # # player_rare_tmp = a_elem['data-rare-type']
                        # player_level_tmp =re.search(
                        #     'hd/(\d+)_(.+).png', str(urllib.parse.unquote(player_image_url))
                        # ).group(2)
                        # gold_cards_info.append(f"{player_level_tmp} {player_rare_tmp}")
                        # if not rare_type and a_elem['data-level'] == 'gold' and player_rare_tmp <= 1:
                        #     new_print(self.fifa_account, '####### another gold card founded')
                        #     bad_player = True
                        #     break
                        # elif rare_type and player_level_tmp == 'gold' and player_rare_tmp == int(player_rare):
                        #     new_print(self.fifa_account, '####### another rare card founded')
                        #     bad_player = True
                        #     break
                    # new_print(self.fifa_account, 'gold cards info : ', gold_cards_info)
                    if current_version in other_rarities:
                        new_print(self.fifa_account, 'same rarities found . bad for discharge ',
                                  current_version, ' -- ', other_rarities)
                        bad_player = True
                else:
                    new_print(self.fifa_account, 'player hasnt any other card')
            except:
                new_print(self.fifa_account, 'player hasnt any other card 2 ', traceback.format_exc())

            output_data = self.get_price_from_futbin_and_futwiz(futbin_id, page_source=resp2)
            if not output_data.get('first_price'):
                new_print(self.fifa_account, 'player has no price , set as bad player')
                bad_player = True
        else:
            output_data = {}
        output_data.update({
            'asset_id': player_asset_id, 'resource_id': player_resource_id,
            'player_name': display_name, 'player_rating': player_rating,
            'bad_player': bad_player, 'rare_id': int(player_rare),
            'bad_for_discharge': bad_player,
        })
        return output_data

    def search_price(self, se, header, persona, nucleos, proxy_ip, proxy_port, proxy_user, proxy_pass, price,
                     player_asset_id, trade_mode=1, position=0, accounts_sbc_id=0, rare=0, pos='', change_pos='',
                     force_manual=0, limit_max_price=999999999, buy=1, change_grade=99, account_id=0, player_found=5,
                     team=0):
        try:
            last_price = price
            futbin_and_futwiz_price = 0
            if (not force_manual) or (not price):
                price_info = self.get_price_from_futbin_and_futwiz(player_asset_id)
                price = price_info.get('price')
                updated_time = price_info.get('update_time')
                if price == 0:
                    price = last_price
                else:
                    price = get_previous_price_grade(price)
                    futbin_and_futwiz_price = 1

                local_data = PlayerCard.objects.filter(asset_id=player_asset_id, rare=rare, team=team,
                                                       position=pos).first()
                price = self.compare_futbin_price_with_local_data(local_data, price, updated_time)

            if price == 0:
                price = 1000
            # get player price
            min_check = max_check = 0
            old_len = 0
            bug_check = 0
            bug = 0
            bought = 0
            increase_count = 0
            decrease_count = 0
            if futbin_and_futwiz_price and (not buy):
                resp = self.search_player(se, header, persona, nucleos, player_asset_id, price, 'max_buy', rare=rare,
                                          pos=pos, account_id=account_id)
                json_resp = resp.json()
                auction_info = json_resp.get('auctionInfo', [])
                if len(auction_info) < 15:
                    futbin_and_futwiz_price = 0

            if (not futbin_and_futwiz_price) or rare > 1:
                change_counter = 0
                while True:
                    if change_counter > change_grade:
                        new_print(self.fifa_account, 'unstable price')
                        return 'unstable'
                    change_counter += 1
                    if price >= limit_max_price:
                        new_print(self.fifa_account, 'max price reached')
                        price = limit_max_price
                        break
                    time.sleep(3)
                    resp = self.search_player(
                        se, header, persona, nucleos, player_asset_id, price, 'max_buy',
                        rare=rare, pos=pos, account_id=account_id)
                    try:
                        json_resp = resp.json()
                    except:
                        new_print(self.fifa_account, 'exception : search player response : ', resp.text)
                        json_resp = resp.json()
                    auction_info = json_resp.get('auctionInfo', [])
                    new_print(self.fifa_account, 'price = ', price, 'length = ', len(auction_info))
                    expire_check = 1
                    if trade_mode == 1:
                        if 0 < len(auction_info) < 21:
                            if len(auction_info) == old_len:
                                if bug_check == 1:
                                    new_print(self.fifa_account, 'bug found')
                                    return 'bug'
                                bug_check = 1
                            old_len = len(auction_info)

                    # for trade in auction_info:
                    #     if trade['expires'] < 3420:
                    #         expire_check = 0
                    if len(auction_info) < player_found and expire_check:
                        if max_check:
                            # price = get_next_price_grade(price)
                            break
                        price = get_next_price_grade(price)
                        min_check = 1
                        if trade_mode == 3:
                            increase_count += 1
                            if increase_count == 5:
                                while True:
                                    price_help = price
                                    if price >= limit_max_price:
                                        new_print(self.fifa_account, 'max price reached')
                                        price = limit_max_price
                                        break
                                    for i in range(10):
                                        price_help = get_next_price_grade(price_help)
                                    resp = self.search_player(se, header, persona, nucleos, player_asset_id, price_help,
                                                              'max_buy', rare=rare, pos=pos
                                                              , account_id=account_id)
                                    json_resp = resp.json()
                                    auction_info = json_resp.get('auctionInfo', [])
                                    if len(auction_info) < player_found and expire_check:
                                        change_counter += 10
                                        if change_counter > change_grade:
                                            new_print(self.fifa_account, 'unstable price')
                                            return 'unstable'

                                        price = price_help
                                        for i in range(20):
                                            price_help = get_next_price_grade(price_help)
                                        resp = self.search_player(se, header, persona, nucleos, player_asset_id,
                                                                  price_help,
                                                                  'max_buy', rare=rare, pos=pos
                                                                  , account_id=account_id)
                                        json_resp = resp.json()
                                        auction_info = json_resp.get('auctionInfo', [])
                                        if len(auction_info) < player_found and expire_check:
                                            change_counter += 20
                                            if change_counter > change_grade:
                                                new_print(self.fifa_account, 'unstable price')
                                                return 'unstable'

                                            price = price_help
                                            for i in range(50):
                                                price_help = get_next_price_grade(price_help)
                                            resp = self.search_player(se, header, persona, nucleos, player_asset_id,
                                                                      price_help, 'max_buy', rare=rare, pos=pos
                                                                      , account_id=account_id)
                                            json_resp = resp.json()
                                            auction_info = json_resp.get('auctionInfo', [])
                                            if len(auction_info) < player_found and expire_check:
                                                change_counter += 50
                                                if change_counter > change_grade:
                                                    new_print(self.fifa_account, 'unstable price')
                                                    return 'unstable'

                                                price = price_help

                                                for i in range(100):
                                                    price_help = get_next_price_grade(price_help)
                                                resp = self.search_player(
                                                    se, header, persona, nucleos, player_asset_id,
                                                    price_help, 'max_buy', rare=rare, pos=pos,
                                                    account_id=account_id)
                                                json_resp = resp.json()
                                                auction_info = json_resp.get('auctionInfo', [])
                                                if len(auction_info) < player_found and expire_check:
                                                    price = price_help
                                                    change_counter += 100
                                                    if change_counter > change_grade:
                                                        new_print(self.fifa_account, 'unstable price')
                                                        return 'unstable'
                                    else:
                                        break

                                increase_count = 0

                    else:
                        if min_check:
                            price = get_previous_price_grade(price)
                            break
                        price = get_previous_price_grade(price)
                        max_check = 1
                        if trade_mode == 3:
                            decrease_count += 1
                            if decrease_count == 10:
                                price_help = price
                                for i in range(20):
                                    price_help = get_previous_price_grade(price_help)
                                if price_help > 400:
                                    resp = self.search_player(se, header, persona, nucleos, player_asset_id, price_help,
                                                              'max_buy', rare=rare, pos=pos
                                                              , account_id=account_id)
                                    json_resp = resp.json()
                                    auction_info = json_resp.get('auctionInfo', [])
                                    if len(auction_info) >= player_found:
                                        price = price_help
                                        change_counter += 20
                                        if change_counter > change_grade:
                                            new_print(self.fifa_account, 'unstable price')
                                            return 'unstable'
                                decrease_count = 0
                    # time.sleep(1)

                    if trade_mode == 1 and min_check and price >= get_next_price_grade(1200):
                        price = get_previous_price_grade(price)
                        break

            try:
                player_card, created = PlayerCard.objects.get_or_create(asset_id=player_asset_id, rare=rare)
            except:
                player_card = PlayerCard.objects.filter(asset_id=player_asset_id, rare=rare).first()

            new_print(self.fifa_account, 'player card created 2 : ', player_card)
            player_card.team = team
            player_card.position = pos
            player_card.price = price
            player_card.update_time = timezone.localtime()
            player_card.save(update_fields=['team', 'position', 'price', 'update_time'])
            new_print(self.fifa_account, 'player_price = ', price)
            if trade_mode == 3:
                return price


        except:
            new_print(self.fifa_account, 'execption in search price', traceback.format_exc())

    def compare_futbin_price_with_local_data(self, local_data, price, updated_time):
        if local_data:
            new_print(self.fifa_account, 'local data found , compare futbin price with local ',
                      local_data, ' -- ', price, ' -- ', updated_time)
            if updated_time.find('secs') == -1 and local_data.update_time:
                if updated_time.find('mins') != -1:
                    updated_time_min = updated_time.split()
                    futbin_updated_time = timezone.localtime() - timedelta(minutes=int(updated_time_min[0]))
                    new_print(self.fifa_account, 'futbin update time , ', futbin_updated_time,
                              local_data.update_time.astimezone(get_current_timezone()))
                    if futbin_updated_time < local_data.update_time.astimezone(get_current_timezone()):
                        new_print(self.fifa_account, 'local data is updater than futbin', local_data.price)
                        price = local_data.price
                elif updated_time.find('hour') != -1:
                    updated_time_hour = updated_time.split()
                    futbin_updated_time = timezone.localtime() - timedelta(hours=int(updated_time_hour[0]))
                    new_print(self.fifa_account, 'futbin update time 2 , ', futbin_updated_time,
                              local_data.update_time.astimezone(get_current_timezone()))
                    if futbin_updated_time < local_data.update_time.astimezone(get_current_timezone()):
                        new_print(self.fifa_account, 'local data is updater than futbin', local_data.price)
                        price = local_data.price
        return price

    def bid_trade(self, se, header, trade_id, data, safe=1):
        if safe:
            options_header = self.get_ea_options_header(method='PUT')

            resp = se.options(
                f'{fifa_23_address}/trade/{trade_id}/bid',
                headers=options_header)
            new_print(self.fifa_account, 'bid options time = ', resp.elapsed.total_seconds())
        resp = se.put(
            f'{fifa_23_address}/trade/{trade_id}/bid', data=data, headers=header)
        return resp

    # def force_get(self, link, se=requests.session(), headers={}):
    #     new_print(self.fifa_account, link)
    #     while True:
    #         try:
    #             return se.get(link, headers=headers)
    #         except:
    #             new_print(self.fifa_account, traceback.format_exc())
    #             new_print(self.fifa_account, 'force get error')

    def check_trade(self, se, header, trade_id):

        options_header = self.get_ea_options_header()
        se.options(
            f'{fifa_23_address}/trade/status/lite?tradeIds={str(trade_id)}', headers=options_header)
        resp = force_get(
            f'{fifa_23_address}/trade/status/lite?tradeIds={str(trade_id)}', self.fifa_account, se, header)
        return resp

    def search_player(self, se, header, persona, nucleos, player_id, max_price, search_type, number='21', start='0',
                      rare=0, pos='', link='', safe=1, account_id=0, random_params=False):
        # print 'in search'
        rare_item = ''
        if rare > 1:
            rare_item = 'SP'

        if account_id and safe:
            self.check_search_count(account_id)
            # cursor2.execute('update transfers set search_number = %s where id = %s', (search_number + 1, account_id))
            # conn2.commit()

            # fifa_account.search_number += 1
            # fifa_account.save()
            # new_print(self.fifa_account, 'account id = ', account_id, 'search number = ',
            #           fifa_account.search_number + 1)

        # time.sleep(1)
        # while True:
        #     if main_dic['temp_number_of_searchs'] >= 60:
        #         time.sleep(1)
        #     else:
        #         break
        try:
            sp = ''
            if search_type == 'max_bid':
                sp = 'macr'
            elif search_type == 'max_buy':
                sp = 'maxb'
            search_part = ''
            if sp:
                search_part = '&' + sp + '=' + str(max_price)
                if random_params:
                    gppg = get_previous_price_grade
                    search_part = search_part + f'&micr={gppg(gppg(gppg(max_price)))}'
                    # search_part = search_part + f'&macr={random.choice([3000000, 3010000, 3020000, 3030000, 3040000, 3050000])}'
            pos_part = ''
            if pos:
                pos_part = '&pos=' + pos

            rare_part = ''
            rarity = ''
            if rare_item:
                # rare_part = '&rare=SP'
                rarity = '&rarityIds=%s' % rare
            if not link:
                link = f'{fifa_23_address}/transfermarket?start=%s&num=%s&type=player&maskedDefId=%s%s%s%s%s' % (
                    start, number, player_id, search_part, rare_part, pos_part, rarity)
            if safe:
                options_header = self.get_ea_options_header()
                se.options(link, headers=options_header)

            # resp = force_get(link,se, header)
            resp = se.get(link, headers=header)
            try:
                json_resp = resp.json()
                auction_info = json_resp['auctionInfo']
            except:
                new_print(self.fifa_account, 'search auction error', resp.text)
                time.sleep(2)
                resp = force_get(link, self.fifa_account, se, header)
                # print 'new search result = ',resp.content
            # print 'link =', link
            # print "main_dic['header'] = ",main_dic['header']
            # print 'resp.content = ', resp.content
            # time.sleep(10)

            if safe:
                pass
                # se.options('https://pin-river.data.ea.com/pinEvents', headers=main_dic['pin_enevts_option_header'])
                # now_time = datetime.now()
                # ea_now_time = now_time + timedelta(hours=7, minutes=30)
                # ea_now_time_date = str(ea_now_time.date())
                # ea_now_time_time = str(ea_now_time.time())[:-3]
                # ea_now_time_plus = ea_now_time + timedelta(seconds=1)
                # ea_now_time_plus_date = str(ea_now_time_plus.date())
                # ea_now_time_plus_time = str(ea_now_time_plus.time())[:-3]

                # pin_enevts_data = '''{"custom": {"networkAccess": "W", "service_plat": "%s"}, "et": "client", "events": [
                #     {"type": "menu", "pgid": "Transfer Market Results - List View",
                #      "core": {"s": 20, "pidt": "persona", "pid": "%s", "ts_event": "%sT%sZ",
                #               "en": "page_view", "pidm": {"nucleus": %s}, "dob": "1995-02"}}], "gid": 0, "is_sess": true,
                #                    "loc": "en_US", "plat": "web", "rel": "prod", "taxv": "1.1", "tid": "%s", "tidt": "easku",
                #                    "ts_post": "%sT%sZ", "v": "23.0.2",
                #                    "sid": "%s"}''' % (
                #     self.platform_key, str(persona), ea_now_time_date, ea_now_time_time, str(nucleos), fut_web_number,
                #     header['X-UT-SID'],
                #     ea_now_time_plus_date, ea_now_time_plus_time)
                # try:
                #     se.post('https://pin-river.data.ea.com/pinEvents', data=pin_enevts_data,
                #             headers=self.main_dic['pin_enevts_header'], timeout=2)
                # except:
                #     new_print(self.fifa_account, 'pin events data sent failed')
            # self.main_dic['number_of_searchs'] += 1
            # self.main_dic['temp_number_of_searchs'] += 1

            return resp
        except:
            new_print(self.fifa_account, 'exception in search player', traceback.format_exc())

    def put_item_in_auction_house(self, se, header, data, buy_now_price=0, target_asset_id=0):
        # print 'auction data = ',data
        options_header = self.get_ea_options_header(method='POST')
        se.options(
            f'{fifa_23_address}/auctionhouse',
            headers=options_header)
        if target_asset_id:
            # threading.Thread(target=search_before_bid,
            #                  kwargs={'buy_now_price': buy_now_price, 'target_asset_id': target_asset_id}).start()
            pass
        resp = se.post(f'{fifa_23_address}/auctionhouse', data=data,
                       headers=header)
        # print 'resp.content = ',(resp.content)[:100]
        return resp

    def item_put_for_sale(self, se, header, item_id, trade_id, win_price, worker_key, start_price=0, buy_now_price=0,
                          target_asset_id=0, test_sniper=0, ):
        if not start_price:
            sell_price = win_price + 100
            sell_price_cal_tax = get_round_top_price((sell_price * 100) / 95)
            start_price = get_previous_price_grade(sell_price_cal_tax)
            buy_now_price = sell_price_cal_tax
        if trade_id:
            data = '{"itemData":[{"id":%s,"pile":"trade","tradeId":"%s"}]}' % (item_id, trade_id)
        else:
            data = '{"itemData":[{"id":%s,"pile":"trade"}]}' % item_id
        new_print(self.fifa_account, 'data =', data)
        resp = put_item_for_sale(se, header, data, self.server_key)
        new_print(self.fifa_account, 'put item in pile trade resp 2 : ', resp.text)
        json_resp = resp.json()
        item_resp = json_resp['itemData'][0]
        item_resp_reason = item_resp.get('reason', '')

        if item_resp_reason.find('No such card exists') != -1:
            new_print(self.fifa_account, 'No such card exists')
        elif not item_resp['success']:
            new_print(self.fifa_account, 'some thing is wrong. not try to sell this card.')
        else:

            link = f'{fifa_23_address}/marketdata/item/pricelimits?itemIdList={item_id}'
            resp = se.get(link, headers=header)
            new_print(self.fifa_account, link)
            new_print(self.fifa_account, 'resp = ', resp.text)
            js_resp = resp.json()
            min_price = js_resp[0]['minPrice']
            if min_price > start_price:
                new_print(self.fifa_account, 'Min price is less than limit. Quick sell this item', min_price,
                          start_price)
                resp2 = se.delete(f'{fifa_23_address}/item/{item_id}', headers=header)
                new_print(self.fifa_account, resp2.tex)
                time.sleep(random.randint(1, 3))
                return ''
                # start_price = min_price
                # buy_now_price = get_next_price_grade(min_price)
            if test_sniper:
                for iie in range(10):
                    try:
                        # resp = self.check_trade(self.main_dic[f'se_{worker_key}'],
                        #                         self.main_dic[f'header_{worker_key}'],
                        #                         self.fake_trade_id)
                        resp = self.main_dic[f'se_{worker_key}'].get(
                            f'{fifa_23_address}/user/credits',
                            headers=self.main_dic[f'header_{worker_key}']
                        )
                        # resp = self.search_player(self.main_dic[f'se_{worker_key}'],
                        #                           self.main_dic[f'header_{worker_key}'],
                        #                           self.main_dic[f'persona_id_{worker_key}'],
                        #                           self.main_dic[f'nucleus_id_{worker_key}'],
                        #                           target_asset_id, get_next_price_grade(
                        #         get_next_price_grade(get_next_price_grade(buy_now_price))), 'max_buy'
                        #                           , account_id=self.sender.fifa_account.id)
                        new_print(self.fifa_account, 'test sniper search time = ', resp.elapsed.total_seconds(),
                                  ' test text : ', resp.text[:1000])

                        # if resp.elapsed.total_seconds() > 0.07:
                        if resp.elapsed.total_seconds() > 0.5:
                            text = 'test sniper failed. search time : ' + str(resp.elapsed.total_seconds())
                            self.send_message(bot, 123, text)
                            new_print(self.fifa_account, text, ' result text = ', resp.text)
                            time.sleep(5)
                            if worker_key == 3:
                                self.get_new_sid(self.main_dic[f'se_{worker_key}'], self.catcher, 'catcher')
                            else:
                                self.get_new_sid(self.main_dic[f'se_{worker_key}'], self.sender, 'sender')
                        else:
                            # time.sleep(0.5)
                            break
                    except:
                        time.sleep(2)
                        new_print(self.fifa_account, 'first driver session expired')
                        if worker_key == 3:
                            self.get_new_sid(self.main_dic[f'se_{worker_key}'], self.catcher, 'catcher')
                        else:
                            self.get_new_sid(self.main_dic[f'se_{worker_key}'], self.sender, 'sender')
                second_driver_checker_counter = 0
                while True:
                    second_driver_checker_counter += 1
                    if second_driver_checker_counter > 2:
                        text = 'user is online %s' % self.receiver.fifa_account.user_name
                        self.send_message(bot, 123, text)
                        self.receiver.refresh_from_db()
                        self.receiver.error_description = "user is online"
                        self.receiver.has_error = True
                        self.receiver.save()
                        return 'change receiver'
                    # resp = self.check_trade(self.main_dic['se_2'], self.main_dic['header_2'], self.fake_trade_id)
                    self.main_dic['se_2'].headers.update(self.main_dic['header_2'])
                    resp = self.main_dic['se_2'].get(f'{fifa_23_address}/user/credits')
                    try:
                        new_print(self.fifa_account, 'check trade time = ', resp.elapsed.total_seconds(),
                                  'check trade result = ', str(resp.json()))
                        resp.json()
                        if resp.text.find('expired session') != -1:
                            raise Exception('session expired %s' % self.receiver.fifa_account.user_name)
                        break
                    except:
                        time.sleep(5)
                        new_print(self.fifa_account, 'second driver session expired , ', traceback.format_exc())
                        self.get_new_sid(self.main_dic['se_2'], self.receiver, 'receiver')
                time.sleep(0.5)
                new_print(self.fifa_account, 'sleep after test sniper 5 sec')
                time.sleep(5)
            new_print(self.fifa_account, 'startingBid = ', start_price, 'buyNowPrice = ', buy_now_price)

            data = json.dumps({"itemData": {"id": item_id}, "startingBid": start_price, "duration": 3600,
                               "buyNowPrice": buy_now_price})
            new_print(self.fifa_account, 'put item in action house , data : ', data)
            sell_resp = self.put_item_in_auction_house(se, header, data, buy_now_price=buy_now_price,
                                                       target_asset_id=target_asset_id)
            if sell_resp.text:
                # self.main_dic['win_controller_count'] += 1
                # self.main_dic['temp_win_controller'] += 1
                return sell_resp
            else:
                new_print(self.fifa_account, 'problem in listing. account : ', ' text : ', sell_resp.text, ' status : ', resp)
        # try:
        #     return sell_resp
        # except:
        #     pass

    def update_credit(self, account_id, se, header, active_trades=False, expire_trades=False):

        # resp = se.get(f'{fifa_23_address}/watchlist',
        #               headers=header)
        # json_resp = resp.json()
        # credit = json_resp['credits']
        credit = get_credit_web(account_id, se, header, active_trades=active_trades, expire_trades=expire_trades).get('credits')
        fifa_account = FifaAccount.objects.filter(id=account_id).first()
        # fifa_account.refresh_from_db()
        fifa_account.credit = credit
        fifa_account.save(update_fields=['credit'])
        return credit

    def get_trade_pile(self, se, header):
        se.options(
            f'{fifa_23_address}/tradepile',
            headers=self.main_dic['options_header'])
        resp = force_get(
            f'{fifa_23_address}/tradepile',
            self.fifa_account, se, header)
        return resp

    def get_plus_credit(self, se, header):
        resp = se.get(f'{fifa_23_address}/watchlist', headers=header)
        json_resp = resp.json()
        credit = json_resp['credits']
        resp = self.get_trade_pile(se, header)
        json_resp = resp.json()
        trades = json_resp.get('auctionInfo', [])
        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
        return credit

    def set_account_proxy(self, account_id, se, proxy_id, proxy_ip, proxy_port, proxy_user, proxy_pass):
        proxies = {
            'http': f'http://{proxy_user}:{proxy_pass}@{proxy_ip}:{proxy_port}',
            'https': 'http://%s:%s@%s:%s' % (proxy_user, proxy_pass, proxy_ip, proxy_port)
        }
        se.proxies.update(proxies)
        new_print(self.fifa_account, 'set account proxy , account id : ', account_id, ' proxy data : ', proxy_id, proxy_ip, proxy_port)
        try:
            resp = se.get("https://icanhazip.com/")
            new_print(self.fifa_account, 'set_account_proxy proxy set resp = ', resp.text)
        except:
            text = 'cant set this proxy 2 %s account %s --- %s' % (proxy_id, account_id, traceback.format_exc())
            self.send_message(bot, 123, text)
            new_print(self.fifa_account, text)
            return 'failed'
        fifa_account = FifaAccount.objects.filter(id=account_id).first()
        fifa_account.proxy = FifaProxy.objects.get(id=proxy_id)
        fifa_account.save()

        new_print(self.fifa_account, 'proxy_id = ', proxy_id)
        return 'ok'

    def set_proxy(self, account_id, se, change=0):
        fifa_account = FifaAccount.objects.filter(id=account_id).first()
        last_proxy_id = 0
        account_proxy = fifa_account.proxy
        if change:
            last_proxy_id = account_proxy.id
            fifa_account.proxy = None
            fifa_account.save(update_fields=['proxy'])
            account_proxy = None
        temp_set_proxy = 0
        if not account_proxy:
            fifa_proxy_list = FifaProxy.objects.exclude(ip_address=change).filter(type_name='mule').annotate(
                usage_count=Coalesce(Subquery(FifaAccount.objects.filter(
                    # Q(delete_console_reason=None) | Q(delete_console_reason=''),
                    proxy__id=OuterRef('pk'),
                ).values('proxy').annotate(
                    use_count=Count('id')
                ).values('use_count'), output_field=IntegerField()), Value(0))
            ).order_by('usage_count')
            lowest_use = fifa_proxy_list.first()
            if lowest_use:
                status = self.set_account_proxy(account_id, se, lowest_use.id, lowest_use.ip_address, lowest_use.port,
                                                lowest_use.user_name, lowest_use.password)
                if status == 'failed':
                    new_print(self.fifa_account, 'proxy set failed 2 . ', lowest_use)
                    return '', '', '', '', se
                account_proxy = lowest_use
            else:
                raise Exception('No Lowest Proxy Found')

        PROXY_HOST = account_proxy.ip_address  # rotating proxy or host
        PROXY_PORT = account_proxy.port  # port
        PROXY_USER = account_proxy.user_name  # self.username
        PROXY_PASS = account_proxy.password  # self.password
        if not temp_set_proxy:
            try:
                proxies = {
                    'http': f'http://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}:{PROXY_PORT}',
                    'https': 'http://%s:%s@%s:%s' % (PROXY_USER, PROXY_PASS, PROXY_HOST, PROXY_PORT)
                }
                se.proxies.update(proxies)
                resp = se.get("https://icanhazip.com/")
                new_print(self.fifa_account, 'set proxy , account : ', account_id, 'proxy set resp = ', resp.text,
                          ' proxy data : ', PROXY_USER, '  ', PROXY_PASS)
            except:
                new_print(self.fifa_account, 'error  : 79', traceback.format_exc())
                text = 'proxy is expired for account %s' % fifa_account.user_name
                new_print(self.fifa_account, text)
                return '', '', '', '', 0, se

        return PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASS, account_proxy.id, se

    def send_message(self, bot, chat_id, text, message_type=None, message_thread_id=None):
        try:
            new_print(self.fifa_account, 'sending on telegram : ', text)
            close_old_connections()
            TelegramMessage.objects.create(
                fifa_account=self.fifa_account,
                message_type=message_type,
                text=text
            )
            if message_thread_id is None:
                chat_id = ARZBAZI_REPORT_GROUP_ID
            if message_thread_id:
                url = f'https://api.telegram.org/bot{FIFA_REPORT_TOKEN}/sendMessage'
                params = {
                    'chat_id': ARZBAZI_REPORT_GROUP_ID,
                    'text': text,
                    'message_thread_id': message_thread_id
                }
                result = requests.get(url, params=params)
                if result.status_code != 200:
                    new_print(self.fifa_account, 'sending on telegram in topic error : ', result.text)
            else:
                bot.sendMessage(chat_id, text)

            if TelegramMessage.objects.filter(
                create_time__gte=timezone.localtime() - timezone.timedelta(hours=24),
                fifa_account=self.fifa_account, text=text
            ).count() <= 1 and message_type == 'error':
                chat_id = '-1001802370673'  # گروه اجرایی فات پلاس
                bot.sendMessage(chat_id, text)
        except:
            new_print(self.fifa_account, 'except in send message , error 42 : ', traceback.format_exc())

    def get_new_sid(self, se, account: SniperAccount, account_type):
        if account_type == 'sender':
            account_key = '_1'
            worker_key = 1
        elif account_type == 'catcher':
            account_key = '_3'
            worker_key = 3
        else:
            account_key = '_2'
            worker_key = 2
        new_print(self.fifa_account, 'get new sid , sniper bot ', account)
        account.refresh_from_db()
        fifa_account = account.fifa_account
        fifa_account.refresh_from_db()
        new_print(fifa_account, 'get new sid for sniper bot')
        if (timezone.localtime() - self.last_time_get_new_sid).total_seconds() < 120:
            self.danger_get_new_sid_counter += 1
            if self.danger_get_new_sid_counter > 10:
                account.has_error = True
                account.error_description = 'too many login'
                account.save(update_fields=['has_error', 'error_description'])
                self.send_message(bot, 123, f'account {fifa_account.user_name} too many login')
                raise Exception('too many login')
        if fifa_account.need_captcha:
            return
        if fifa_account.access_token and fifa_account.nucleus_id:
            logined_with_new_sid = False
            try:
                if self.get_new_sid_by_access_token(worker_key, fifa_account, sid=fifa_account.sid):
                    time.sleep(0.5)
                    self.update_credit(fifa_account.id, self.main_dic[f'se{account_key}'], self.main_dic[f'header{account_key}'])
                    time.sleep(0.5)
                    logined_with_new_sid = True
                    return {'status_bool': True}
            except:
                new_print(fifa_account, 'error 47 : ', traceback.format_exc())
                close_old_connections()
            if not logined_with_new_sid:
                new_print(self.fifa_account, 'not logined with new sid , try to login with requests')
                try:
                    new_print(self.fifa_account,
                              'cant get_new_sid_by_access_token so try to login with requests')
                    if fifa_account.console:
                        proxy_ip, proxy_port, proxy_user, proxy_pass, proxy_id = '', '', '', '', ''
                    else:
                        proxy_ip, proxy_port, proxy_user, proxy_pass, proxy_id = self.set_proxy(
                            fifa_account.id, self.main_dic[f'se{account_key}'])
                    fifa_backup = fifa_account.account_backup_code.first()
                    app_auth = fifa_backup.app_code
                    login_log = AccountLoginLog.objects.create(fifa_account=self.fifa_account, login_method=1)
                    login_result = LoginWithRequest(
                        fifa_account=fifa_account
                    ).new_login(
                        email=fifa_account.user_name, password=fifa_account.password, totp=app_auth,
                        proxy_ip=proxy_ip,
                        proxy_port=proxy_port, proxy_user=proxy_user, proxy_pass=proxy_pass,
                        platform=fifa_account.platform)
                    if login_result.get('status_bool') is False:
                        new_print(self.fifa_account, 'login status false , result is : ', login_result)
                        if login_result.get('error') == 'need create club':
                            raise Exception('need create club')
                    else:
                        n_session = login_result.get('session')
                        n_sid = login_result.get('sid')
                        n_fcas_sid = login_result.get('fcas_sid')
                        n_persona_id = login_result.get('persona_id')
                        n_nucleus_id = login_result.get('nucleus_id')
                        n_access_token = login_result.get('access_token')
                        time.sleep(2)
                        fifa_account.refresh_from_db()
                        fifa_account.access_token = n_access_token
                        fifa_account.nucleus_id = n_nucleus_id
                        fifa_account.persona_id = n_persona_id
                        fifa_account.sid = n_sid
                        fifa_account.save(
                            update_fields=['access_token', 'nucleus_id', 'persona_id', 'sid']
                        )
                        login_log.login_status = 1
                        login_log.save(update_fields=['login_status'])
                        self.main_dic[f'se{account_key}'] = n_session
                        self.main_dic[f'header{account_key}'] = n_session.headers
                        self.fcas_sid = n_fcas_sid
                        new_print(self.fifa_account, 'login with request success 1')
                        return {'status_bool': True}
                except:
                    new_print(self.fifa_account, 'cant login with requests, error : ', traceback.format_exc())
                    close_old_connections()

        account.fifa_account.driver = 1
        account.fifa_account.save()
        refresh_count = 0
        while True:
            proxy_data = account.fifa_account.proxy
            if refresh_count >= 1:
                break
            refresh_count += 1
            new_print(self.fifa_account, 'number of refresh count in get new sid = ', refresh_count)
            try:
                self.main_dic['driver%s' % account_key].get(
                    'https://www.ea.com/ea-sports-fc/ultimate-team/web-app/')
            except:
                self.main_dic[
                    'driver%s' % account_key], futbin, need_to_close_ultimate_in_console, need_to_create_club = login_to_account(
                    account.fifa_account.user_name, account.fifa_account.password,
                    account.fifa_account.account_backup_code.last().backup_code,
                    app_auth=account.fifa_account.account_backup_code.last().app_code,
                    proxy_ip=proxy_data.ip_address,
                    proxy_port=proxy_data.port,
                    proxy_user=proxy_data.user_name,
                    proxy_pass=proxy_data.password,
                )
            elem = wait_for_element('class', 'one', 'view-navbar-currency-coins', special='captcha',
                                    driver=self.main_dic['driver%s' % account_key])
            self.main_dic['driver%s' % account_key].get_screenshot_as_file(
                self.file_path + '/logs/sid%s.png' % str(account.fifa_account.id))
            new_print(self.fifa_account, 'view-navbar-currency-coins = ', elem)
            if elem:
                break
            if not elem:
                elem = wait_for_element('xpath', 'one', "//h2[contains(text(),'Verification Required')]",
                                        special='break',
                                        driver=self.main_dic['driver%s' % account_key])
                if not elem:
                    try:
                        new_print(self.fifa_account, 'not elem')
                        elem = wait_for_element('class', 'one', 'call-to-action',
                                                driver=self.main_dic['driver%s' % account_key])
                        ActionChains(self.main_dic['driver%s' % account_key]).move_to_element(
                            elem).click().perform()
                        elem = wait_for_element('class', 'one', 'view-navbar-currency-coins',
                                                driver=self.main_dic['driver%s' % account_key])
                        if elem:
                            break
                    except:
                        pass
                else:
                    new_print(self.fifa_account, 'captcha found')
                    self.main_dic['driver%s' % account_key].get_screenshot_as_file(
                        self.file_path + '/logs/captcha%s.png' % str(account.fifa_account.id))

                    # #new part
                    # element = self.main_dic['driver%s'%account_key].find_element_by_xpath("//div[@id='FunCaptcha']")
                    # location = element.location
                    # size = element.size

                    account.fifa_account.refresh_from_db()
                    account.fifa_account.need_captcha = 1
                    account.fifa_account.save()
                    self.send_message(bot, -1001208022772,
                                      'captcha need . automatic solve for account id %s' % (
                                          account.fifa_account.user_name))

                    cookies = self.main_dic['driver%s' % account_key].get_cookies()
                    nx_mpcid = ''
                    for cookie in cookies:
                        if str(cookie['name']) == '_nx_mpcid':
                            nx_mpcid = str(cookie['value'])
                    if not nx_mpcid:
                        text = 'no nx_mpcid found for account %s' % account.fifa_account.user_name
                        self.send_message(bot, 123, text)
                        new_print(self.fifa_account, text)
                        time.sleep(300)
                        return
                    seassion_id = self.main_dic['driver%s' % account_key].execute_script(
                        "return services.Authentication.utasSession.id")
                    neclesu_id = self.main_dic['driver%s' % account_key].execute_script(
                        "return services.User.getUser().id")
                    payload = {"proxy_port": str(proxy_data.port), "proxy_ip": proxy_data.ip_address,
                               "proxy_user": "", "fingerprint": "",
                               "device": "WEB",
                               "userAgent": user_agent,
                               "console": "PS", "proxy_pass": "", "nx_mpcid": nx_mpcid, "proxy_type": "HTTP",
                               "sessionId": seassion_id, "futEmail": account.fifa_account.user_name,
                               "api_key": "ccbf62d7921a1c4b4f9cdc0fa18ece52", "nucleusId": neclesu_id,
                               "user": "simonhains", "pass": "zmvLAS0193"}

                    # data = {
                    #     "api_key": "ccbf62d7921a1c4b4f9cdc0fa18ece52",
                    #     "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36",
                    #     "nx_mpcid": nx_mpcid,
                    #     "nucleusId": self.main_dic['driver%s'%account_key].execute_script("return services.User.getUser().id"),
                    #     "sessionId":  self.main_dic['driver%s'%account_key].execute_script("return services.Authentication.utasSession.id"),
                    #     "console": "PS",
                    #     "device": "WEB",
                    #     "futEmail": username,
                    #     "fingerprint": "",
                    #     "proxy_ip": proxy_data[0],
                    #     "proxy_port": str(proxy_data[1]),
                    #     "proxy_user": "",
                    #     "proxy_pass": "",
                    #     "proxy_type": "HTTP"
                    #     }
                    headers = {
                        'content-type': "application/json"
                    }
                    new_print(self.fifa_account, 'before request')
                    new_print(self.fifa_account, 'data = ', payload)
                    resp = se.post('http://api.de-ltd.co.uk/fcapi/solve.php', json=payload, headers=headers)
                    try:
                        json_resp = resp.json()
                        if json_resp['EA_VALIDATED'] == 1 and json_resp['FC_SOLVED'] == 1:
                            account.fifa_account.refresh_from_db()
                            account.fifa_account.need_captcha = 0
                            account.fifa_account.save()

                            self.send_message(bot, -1001208022772,
                                              'captcha solved for account_id %s' % account.fifa_account.user_name)
                            time.sleep(5)
                            self.main_dic['driver%s' % account_key].get(
                                'https://www.ea.com/ea-sports-fc/ultimate-team/web-app/')
                            wait_for_element('class', 'one', 'view-navbar-currency-coins',
                                             driver=self.main_dic['driver%s' % account_key])
                            refresh_count = 2

                            # break
                        else:
                            text = 'cant solve captcha for %s' % account.fifa_account.user_name
                            self.send_message(bot, 'critical', text)
                            new_print(self.fifa_account, text)
                            time.sleep(300)
                            return
                    except:
                        new_print(self.fifa_account, 'error 84 : ', traceback.format_exc())
                        text = 'cant solve captcha for %s' % account.fifa_account.user_name
                        self.send_message(bot, 'critical', text)
                        new_print(self.fifa_account, text)
                        time.sleep(300)
                        return

        elem = wait_for_element('xpath', 'one', "//button[contains(text(),'Continue')]", special='break',
                                driver=self.main_dic['driver%s' % account_key])
        t_count = 0
        if elem:
            while True:
                t_count += 1
                if t_count >= 20:
                    break
                elem = wait_for_element('xpath', 'one', "//button[contains(text(),'Continue')]",
                                        special='break', driver=self.main_dic['driver%s' % account_key])
                if elem:
                    elem.click()
                else:
                    break
                time.sleep(0.5)

        self.main_dic['sid%s' % account_key] = self.main_dic['driver%s' % account_key].execute_script(
            "return services.Authentication.utasSession.id")

        self.main_dic['nucleus_id%s' % account_key] = self.main_dic['driver%s' % account_key].execute_script(
            "return services.User.getUser().id")
        persona = self.main_dic['driver%s' % account_key].execute_script(
            "return services.User.getUser().personas[0]['id']")
        persona = str(persona)
        # print persona
        # tag = "'id': "
        # persona_id_begin = persona.find(tag) + len(tag)
        # persona_id_end = persona.find(',', persona_id_begin)
        # persona_id = persona[persona_id_begin:persona_id_end]
        self.main_dic['persona_id%s' % account_key] = int(persona)
        new_print(self.fifa_account, 'persona_id = ', self.main_dic['persona_id%s' % account_key])
        new_print(self.fifa_account, 'nucleus_id = ', self.main_dic['nucleus_id%s' % account_key])
        new_print(self.fifa_account, 'sid = ', self.main_dic['sid%s' % account_key])

        # global pin_enevts_data
        self.main_dic['header%s' % account_key] = {
            'Content-Type': 'application/json',
            'Origin': 'https://www.ea.com',
            'Referer': 'https://www.ea.com/',
            'User-Agent': user_agent,
            'X-UT-SID': self.main_dic['sid%s' % account_key],
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'en-US,en;q=0.5',
            'Connection': 'keep-alive',
            'Host': fifa_host,
        }
        self.main_dic['driver%s' % account_key].get_screenshot_as_file('get_new_sid_tmp.png')
        self.main_dic['driver%s' % account_key].get_screenshot_as_file(
            os.path.join(
                BASE_DIR,
                'sniper/proofs/%s_after.png' % account.fifa_account.user_name
            )
        )

        self.main_dic['driver%s' % account_key].close()
        account.fifa_account.refresh_from_db()
        account.fifa_account.driver = 0
        account.fifa_account.save()

        #
        # pin_enevts_data = {"custom": {"networkAccess": "G", "service_plat": "ps4"}, "et": "client", "events": [
        #     {"type": "menu", "pgid": "Hub - Transfers",
        #      "core": {"s": 3, "pidt": "persona", "pid": "1973380164", "ts_event": "2019-03-14T11:42:06.830Z",
        #               "en": "page_view", "pidm": {"nucleus": 1007662553918}, "dob": "1988-02"}}], "gid": 0,
        #                    "is_sess": True,
        #                    "loc": "en_US", "plat": "web", "rel": "prod", "taxv": "1.1", "tid": "FUT19WEB",
        #                    "tidt": "easku",
        #                    "ts_post": "2019-03-14T11:42:07.331Z", "v": "19.1.0",
        #                    "sid": sid}

        time.sleep(20)

    def check_account_problems(self, account: SniperAccount, driver, nucleus):
        error = ''
        elem = wait_for_element('xpath', 'one', "//h2[contains(text(),'Signed Into Another Device')]", special='break',
                                driver=driver)
        if elem:
            error = 'console login'
        else:
            elem = wait_for_element('xpath', 'one',
                                    "//p[contains(text(),'It looks like your EA Account doesn’t have a FUT')]",
                                    special='break',
                                    driver=driver)
            if elem:
                error = 'no club'
            else:
                try:
                    trade_access = driver.execute_script(
                        "return services.User.repository._collection[%s]['tradeAccess']" % nucleus)
                    new_print(self.fifa_account, 'trade access =', trade_access)

                    if str(trade_access) == '0':
                        elem_transfer = wait_for_element('class', 'one', 'icon-transfer', driver=driver,
                                                         special='fast_break')
                        if elem_transfer:
                            error = 'account not yet access'
                    if str(trade_access) == '3' or str(trade_access) == '1':
                        error = 'account transfer is ban'
                except:
                    new_print(self.fifa_account, 'error 85 : ', traceback.format_exc())

        if error:
            account.refresh_from_db()
            account.error_description = error
            account.has_error = True
            account.save()
            text = error + ' ' + account.fifa_account.user_name
            new_print(self.fifa_account, 'error = ', error)
            self.send_message(bot, 'critical', text)
        return error

    def third_account_search(self, buy_now_price, target_asset_id, rare=0):
        resp = self.search_player(self.main_dic['se_3'], self.main_dic['header_3'], self.main_dic['persona_id_3'],
                                  self.main_dic['nucleus_id_3']
                                  , target_asset_id, get_next_price_grade(buy_now_price), 'max_buy', safe=0,
                                  rare=rare)
        # new_print(self.fifa_account,'search_player se 2 time = ', resp.elapsed.total_seconds())
        # delay_start = time.time()
        json_resp = resp.json()
        auction_info = json_resp.get('auctionInfo', [])
        found = 0
        bid_buy_now_price = 0
        for trade in auction_info:
            # if trade['tradeId'] == trade_id:
            #     bid_buy_now_price = trade['buyNowPrice']
            found = 1
            new_print(self.fifa_account, 'third found ******', trade['tradeId'])
            break
        if not found:
            new_print(self.fifa_account, 'second couldnt found')

    def check_search_count(self, account_id, add_search_count=True):
        if add_search_count:
            FifaAccountSearch.objects.create(fifa_account_id=account_id, search_time=timezone.localtime())
        fifa_account = FifaAccount.objects.filter(id=account_id).first()
        if fifa_account:
            search_number = fifa_account.account_search.filter(
                search_time__gt=timezone.localtime() - timezone.timedelta(hours=24)).count()
            new_print(self.fifa_account, 'search_number = ', search_number, ' account : ', fifa_account)
            if (search_number + 1 > self.account_high_search_count):
                new_print(self.fifa_account, 'search number is more than defined max search : ', search_number)
                if fifa_account == self.sender.fifa_account:
                    # self.sender.refresh_from_db()
                    self.sender.has_error = 1
                    self.sender.error_description = 'sender high search'
                    self.sender.save(update_fields=['has_error', 'error_description'])
                    self.handle_end_bot()
                else:
                    # self.receiver.refresh_from_db()
                    self.receiver.has_error = 1
                    self.receiver.error_description = 'receiver high search'
                    self.receiver.save(update_fields=['has_error', 'error_description'])
                    self.handle_end_bot()
                return

    def search_before_bid(self, worker_key, buy_now_price, target_asset_id, trade_id='', rare=0,
                          bid_after_search=False):
        # for i in range(2):
        # new_se = requests.session()
        search_counter = 0
        while True:
            # if self.main_dic.get('persona_id_2'):
            #     person_id = self.main_dic.get('persona_id_2')
            # elif self.receiver.fifa_account.persona_id:
            #     person_id = self.receiver.fifa_account.persona_id
            # else:
            #     new_print(self.fifa_account, 'Warning : can not find persona id ', self.main_dic.get('persona_id_2'),
            #               self.receiver.fifa_account.persona_id)
            #     raise Exception('Warning : can not find persona id ')
            # if self.main_dic.get('nucleus_id_2'):
            #     nucleus_id = self.main_dic.get('nucleus_id_2')
            # elif self.receiver.fifa_account.nucleus_id:
            #     nucleus_id = self.receiver.fifa_account.nucleus_id
            # else:
            #     new_print(self.fifa_account, 'Warning : can not find nucleus id ', self.main_dic.get('nucleus_id_2'),
            #               self.receiver.fifa_account.nucleus_id)
            #     raise Exception('Warning : can not find persona id ')
            if worker_key == 3:
                account_id = self.catcher.fifa_account.id
            elif worker_key == 2:
                account_id = self.receiver.fifa_account.id
            elif worker_key == 1:
                account_id = self.sender.fifa_account.id
            else:
                new_print(self.fifa_account, 'search before bid , can not find worker key')
                return
            resp = self.search_player(
                self.main_dic[f'se_{worker_key}'], self.main_dic[f'header_{worker_key}'],
                self.main_dic[f'persona_id_{worker_key}'], self.main_dic[f'nucleus_id_{worker_key}'],
                target_asset_id, get_next_price_grade(buy_now_price), 'max_buy', safe=0,
                account_id=account_id, rare=rare, random_params=True)
            # new_print(self.fifa_account,'search_player se 2 time = ', resp.elapsed.total_seconds())
            # delay_start = time.time()
            json_resp = resp.json()
            auction_info = json_resp.get('auctionInfo', [])
            found = 0
            bid_buy_now_price = 0
            for trade in auction_info:
                # if trade['tradeId'] == trade_id:
                #     bid_buy_now_price = trade['buyNowPrice']
                found = 1
                bid_resp = None
                if bid_after_search:
                    search_resp_seconds = resp.elapsed.total_seconds()
                    # این عدد برای تاخیر ارسال خرید کچر بعد از سرچ ریسیور اضافه شده و در جواب 0.025 بوده است
                    if resp.elapsed.total_seconds() < .04:
                        time.sleep(0.04 - search_resp_seconds)
                    data = json.dumps({"bid": buy_now_price})
                    bid_resp = self.bid_trade(
                        self.main_dic[f'se_{worker_key}'], self.main_dic[f'header_{worker_key}'], trade_id, data,
                        safe=0
                    )
                # new_print(self.fifa_account, 'found ******')
                # self.check_search_count(account_id)
                return resp, bid_resp
            # self.check_search_count(account_id)
            if found:
                break
            if not found:
                new_print(self.fifa_account, 'not found',
                          ' search content = ', auction_info)

                # resp = search_player(self.main_dic['se_3'], self.main_dic['header_3'], self.main_dic['persona_id_3'],
                #                      self.main_dic['nucleus_id_3']
                #                      , target_asset_id, get_next_price_grade(buy_now_price), 'max_buy', safe=0)
                # # new_print(self.fifa_account,'search_player se 2 time = ', resp.elapsed.total_seconds())
                # # delay_start = time.time()
                # json_resp = resp.json()
                # auction_info = json_resp['auctionInfo']
                # found = 0
                # bid_buy_now_price = 0
                # for trade in auction_info:
                #     if trade['tradeId'] == trade_id:
                #         bid_buy_now_price = trade['buyNowPrice']
                #         found = 1
                #         print 'third account found ******'
                #         break
                # if found:
                #
                #     data = '{"bid":%d}' % bid_buy_now_price
                #     # delay_end = time.time()
                #     # print 'delay time = ',delay_end - delay_start
                #     # c = time.time()
                #     # new_se = requests.session()
                #     bid_resp = bid_trade(self.main_dic['se_3'], self.main_dic['header_3'], trade_id, data, safe=0)
                #     new_print(self.fifa_account,'third account bid time = ', bid_resp.elapsed.total_seconds())
                #     # print 'c - b time =', c-b
                #     # print 'c - a time =', c-a
                #     print bid_resp.content
                #     if bid_resp.content == 'Permission Denied' or bid_resp.content == '' or bid_resp.content == 'You are not allowed to bid on this trade':
                #         print 'third account missed this one too ...'
                #     else:
                #         print 'third account won the bid'
                #         json_bid_resp = bid_resp.json()
                #         player_club_id = json_bid_resp['auctionInfo'][0]['itemData']['id']
                #         # resp = item_put_for_sale(self.main_dic['se_2'], self.main_dic['header_2'], player_club_id,
                #         #                          json_bid_resp['auctionInfo'][0]['tradeId'], 0, start_price=get_previous_price_grade(player_price),
                #         #                          buy_now_price=player_price)
                #         player_price = get_previous_price_grade(player_price)
                #         if player_price > 100000:
                #             player_price = get_previous_price_grade(
                #                 get_previous_price_grade(get_previous_price_grade(player_price)))
                #         while True:
                #             try:
                #                 resp = item_put_for_sale(self.main_dic['se_3'], self.main_dic['header_3'], player_club_id,
                #                                          json_bid_resp['auctionInfo'][0]['tradeId'], 0,
                #                                          start_price=get_previous_price_grade(
                #                                              get_previous_price_grade(player_price)),
                #                                          buy_now_price=get_previous_price_grade(player_price))
                #                 print resp.json()
                #                 break
                #             except:
                #                 time.sleep(5)
                #                 print 'third driver session expired'
                #                 get_new_sid(self.main_dic['se_3'], account_3, 'third')
                #         delete_sold_items(self.main_dic['se_3'], self.main_dic['header_3'])
                #         text = "target wasn't in main account search list but it appeared in third account search list and third account bought it with honor"
                #         send_message(bot,123,text)
                #         print text
                # else:
                #     print 'third account couldnt find it too ...'
                # new_print(self.fifa_account, 'search content = ', auction_info)
                if trade_id:
                    new_print(self.fifa_account, 'check trade in search before bid ', (
                        self.check_trade(self.main_dic['se_2'], self.main_dic['header_2'], trade_id)).text)
                    # time.sleep(0.1)
            search_counter += 1
            if search_counter > 0:
                new_print(self.fifa_account, 'search before bid : player not found')
                break
            # if search_counter == 2:
            #     resp = self.search_player(self.main_dic['se_2'], self.main_dic['header_2'],
            #                               self.main_dic['persona_id_2'],
            #                               self.main_dic['nucleus_id_2']
            #                               , target_asset_id,
            #                               get_next_price_grade(get_next_price_grade(buy_now_price)),
            #                               'max_buy', safe=0, rare=rare)
        new_print(self.fifa_account, 'search_counter = ', search_counter)
        return resp, None

    def transfer_coin(self, coins_before=0):
        try:
            self.main_dic['se_1'] = requests.session()
            (self.sender_proxy_ip, self.sender_proxy_port, self.sender_proxy_user, self.sender_proxy_password,
             self.sender_proxy_id, self.main_dic['se_1']
             ) = self.set_proxy(self.sender.fifa_account.id, self.main_dic['se_1'], change=0)
            if not self.sender_proxy_ip:
                self.sender.error_description = 'sender no proxy found'
                self.sender.has_error = True
                self.sender.save(update_fields=['has_error', 'error_description'])
                return 'change sender'

            # sender_proxy_ip = proxy_ip
            # account_1 = [sender[1], sender[2], sender[4], proxy_ip, proxy_port, sender[3], sender[0]]

            self.main_dic['se_2'] = requests.session()
            receiver_proxy_ip, receiver_proxy_port, receiver_proxy_user, receiver_proxy_password, receiver_proxy_id, \
            self.main_dic['se_2'] = self.set_proxy(self.receiver.fifa_account.id, self.main_dic['se_2'], change=0)
            if not receiver_proxy_ip:
                self.receiver.error_description = 'receiver no proxy found'
                self.receiver.has_error = True
                self.receiver.save(update_fields=['has_error', 'error_description'])
                return 'change receiver'
            if receiver_proxy_ip == self.sender_proxy_ip:
                receiver_proxy_ip, receiver_proxy_port, receiver_proxy_user, receiver_proxy_password, receiver_proxy_id, \
                self.main_dic['se_2'] = self.set_proxy(
                    self.receiver.fifa_account.id, self.main_dic['se_2'], change=receiver_proxy_ip)
                if not receiver_proxy_ip:
                    self.receiver.error_description = 'receiver no proxy found'
                    self.receiver.has_error = True
                    self.receiver.save(update_fields=['has_error', 'error_description'])
                    return 'change receiver'
            if self.catcher:
                self.main_dic['se_3'] = requests.session()
                catcher_proxy_ip, catcher_proxy_port, catcher_proxy_user, catcher_proxy_password, catcher_proxy_id, \
                self.main_dic['se_3'] = self.set_proxy(self.catcher.fifa_account.id, self.main_dic['se_3'], change=0)
                if not catcher_proxy_ip:
                    self.catcher.error_description = 'catcher no proxy found'
                    self.catcher.has_error = True
                    self.catcher.save(update_fields=['has_error', 'error_description'])
                    return 'change catcher'
                new_print(self.fifa_account, "self.main_dic['se_3'] = ", self.main_dic['se_3'])
                self.catcher.fifa_account.refresh_from_db()
                self.catcher.fifa_account.driver = 1
                self.catcher.fifa_account.save()
                catcher_login_result = self.sniper_logout_login('catcher', self.catcher, self.catcher.fifa_account)
                error_text = ''
                problem_counter_3 = 0
                if catcher_login_result == 'account not yet access':
                    problem_counter_3 = 2
                    error_text = 'account not yet access'
                    new_print(self.catcher.fifa_account, 'account not yet access')
                elif catcher_login_result == 'account transfer is ban':
                    error_text = 'account transfer is ban'
                    new_print(self.catcher.fifa_account, 'account transfer is ban')
                while True:
                    problem_counter_3 += 1
                    if problem_counter_3 > 3:
                        text = 'account have some issues %s' % self.catcher.fifa_account.user_name
                        self.send_message(bot, 123, text)
                        self.catcher.refresh_from_db()
                        self.catcher.error_description = error_text or "account problem"
                        self.catcher.has_error = True
                        self.catcher.save()
                        return 'change catcher'
                    try:
                        p_catcher_credit = self.update_credit(
                            self.catcher.fifa_account.id, self.main_dic['se_3'], self.main_dic['header_3'])
                        new_print(self.fifa_account, 'catcher credit updated : ', p_catcher_credit)
                        break
                    except:
                        time.sleep(5)
                        new_print(self.fifa_account, 'account problem : ', traceback.format_exc())
                        self.get_new_sid(self.main_dic['se_3'], self.catcher, 'catcher')

            new_print(self.fifa_account, "self.main_dic['se_1'] = ", self.main_dic['se_1'])
            new_print(self.fifa_account, "self.main_dic['se_2'] = ", self.main_dic['se_2'])
            self.sender.fifa_account.refresh_from_db()
            self.sender.fifa_account.driver = 1
            self.sender.fifa_account.save(update_fields=['driver'])
            sender_login_result = self.sniper_logout_login('sender', self.sender, self.sender.fifa_account)
            error_text = ''
            problem_counter_1 = 0
            if sender_login_result == 'account not yet access':
                problem_counter_1 = 2
                error_text = 'account not yet access'
                new_print(self.sender.fifa_account, 'account not yet access')
            elif sender_login_result == 'account transfer is ban':
                error_text = 'account transfer is ban'
                new_print(self.sender.fifa_account, 'account transfer is ban')
            while True:
                problem_counter_1 += 1
                if problem_counter_1 > 3:
                    text = f'account have some issues {self.sender.fifa_account.user_name}'
                    self.send_message(bot, 123, text)
                    self.sender.refresh_from_db()
                    self.sender.error_description = error_text or "account problem"
                    self.sender.has_error = True
                    self.sender.save(update_fields=['has_error', 'error_description'])
                    return 'change sender'
                try:
                    p_sender_credit = self.update_credit(
                        self.sender.fifa_account.id, self.main_dic['se_1'], self.main_dic['header_1'])
                    new_print(self.fifa_account, 'sender credit updated : ', p_sender_credit)
                    break
                except:
                    time.sleep(5)
                    new_print(self.fifa_account, 'account problem : ', traceback.format_exc())
                    self.get_new_sid(self.main_dic['se_1'], self.sender, 'sender')

            p_coins_before = self.sender.coins_before
            if not p_coins_before:
                self.sender.refresh_from_db()
                self.sender.coins_before = p_sender_credit
                self.sender.save(update_fields=['coins_before'])

            self.receiver.refresh_from_db()
            if not coins_before and self.receiver.need_proof:
                receiver_login_result = self.sniper_logout_login(
                    'receiver', self.receiver, self.receiver.fifa_account, use_new_sid=False, close_driver=False)
                self.main_dic['driver_2'].get_screenshot_as_file(
                    os.path.join(
                        BASE_DIR,
                        'sniper/proofs/%s_before.png' % self.receiver.fifa_account.user_name
                    )
                )
                telegram_send_photo(
                    fifa_account=self.fifa_account,
                    photo_path=os.path.join(
                        BASE_DIR, 'sniper/proofs/%s_before.png' % self.receiver.fifa_account.user_name,
                    ),
                    caption=f'# proof for sniper : {self.receiver.fifa_account.user_name}',
                    message_type='info',
                    message_thread_id=ARZBAZI_REPORT_TOPIC_GENERAL_THREAD_MESSAGE_ID
                )
                # bot.sendPhoto(
                #     # -1001632841996,
                #     -1001712554408,
                #     open(
                #         os.path.join(
                #             BASE_DIR,
                #             'sniper/proofs/%s_before.png' % self.receiver.fifa_account.user_name,
                #         ),
                #         'rb'
                #     ),
                #     caption=f'# proof for sniper : {self.receiver.fifa_account.user_name}'
                # )
                self.main_dic['driver_2'].close()
            else:
                receiver_login_result = self.sniper_logout_login('receiver', self.receiver, self.receiver.fifa_account)

            error_text_2 = ''
            problem_counter_2 = 0
            if receiver_login_result == 'account not yet access':
                problem_counter_2 = 2
                error_text_2 = 'account not yet access'
                new_print(self.receiver.fifa_account, 'account not yet access')
            elif receiver_login_result == 'account transfer is ban':
                error_text_2 = 'account transfer is ban'
                new_print(self.receiver.fifa_account, 'account transfer is ban')
            while True:
                problem_counter_2 += 1
                if problem_counter_2 > 2:
                    text = 'account have some issues %s' % self.receiver.fifa_account.user_name
                    self.send_message(bot, 123, text)
                    self.receiver.refresh_from_db()
                    self.receiver.error_description = error_text_2 or "account problem"
                    self.receiver.has_error = True
                    self.receiver.save(update_fields=['has_error', 'error_description'])
                    return 'change receiver'
                try:
                    receiver_credit = self.update_credit(
                        self.receiver.fifa_account.id, self.main_dic['se_2'],
                        self.main_dic['header_2'], active_trades=True, expire_trades=True
                    )
                    new_print(self.receiver.fifa_account, 'receiver credit updated : ', receiver_credit)
                    break
                except:
                    time.sleep(5)
                    new_print(self.fifa_account, 'account problem : ', traceback.format_exc())
                    self.get_new_sid(self.main_dic['se_2'], self.receiver, 'receiver')

            new_print(self.fifa_account, receiver_credit)
            self.receiver.refresh_from_db()
            if not coins_before:
                self.receiver.coins_before = receiver_credit
                self.receiver.save()
                if self.receiver.transfer_amount:
                    self.receiver.transfer_to = receiver_credit + self.receiver.transfer_amount + 4000
                    self.receiver.save(update_fields=['transfer_to'])
                if self.receiver.need_proof:
                    self.receiver.coins_after = receiver_credit + self.receiver.transfer_amount - 2000
                    self.receiver.save(update_fields=['coins_after'])

            # self.main_dic['driver_2'].close()
            # self.main_dic['se_2'] = requests.session()
            # proxies = {'https': 'http://%s:%s' % (account_2[3], account_2[4])}
            # self.main_dic['se_2'].proxies.update(proxies)
            self.sender.fifa_account.driver = 0
            self.sender.fifa_account.save()
            self.receiver.refresh_from_db()
            max_transfer = self.receiver.transfer_to

            receiver_credit_counter = 0

            success_count = 0
            bid_count = 0

            # fake_trade_id = TradeLog.objects.filter(
            #     create_time__gt=timezone.localtime() - timezone.timedelta(days=7)
            # ).exclude(
            #     trade_id__in=['', None],
            # ).last()
            # if fake_trade_id:
            #     fake_trade_id = fake_trade_id.trade_id
            # else:
            #     fake_trade_id = 466355881582
            # data = '{"bid":%d}' % 5000
            # bid_resp = bid_trade(self.main_dic['se_2'], self.main_dic['header_2'], fake_trade_id, data)
            # print 'fake_bid_resp =',bid_resp.content
            # print 'fake_bid_time = ', bid_resp.elapsed.total_seconds()
            # time.sleep(10)
            try_to_find_targets = 0
            while True:
                close_old_connections()
                self.receiver.refresh_from_db()
                if self.receiver.is_done == 1 or self.receiver.has_error == 1:
                    return 'manual deactivate'
                sniper_highest_target_buy_now_price = ConsoleBotSetting.objects.get(name='sniper_highest_target_buy_now_price').int_value
                sniper_lowest_snipe_buy_now_price = ConsoleBotSetting.objects.get(name='sniper_lowest_snipe_buy_now_price').int_value
                new_print(self.fifa_account, 'transfer coin loop started.',
                          ' sniper_highest_target_buy_now_price : ', sniper_highest_target_buy_now_price,
                          ' sniper_lowest_snipe_buy_now_price : ', sniper_lowest_snipe_buy_now_price)

                bid_count += 1
                # if bid_count > 3:
                #     bid_count = 0
                #     print 'sleep for 120 seconds'
                #     # time.sleep(120)
                #     time.sleep(60)
                #     get_new_sid(self.main_dic['se_2'], account_2, 'receiver')
                target_price = 500000

                # receiver_limit

                # while True:
                for iie in range(10):
                    try:
                        receiver_credit = self.update_credit(
                            self.receiver.fifa_account.id, self.main_dic['se_2'], self.main_dic['header_2'])
                        break
                    except:
                        time.sleep(5)
                        new_print(self.fifa_account, 'can not get credit', traceback.format_exc())
                        self.get_new_sid(self.main_dic['se_2'], self.receiver, 'receiver')
                # receiver_credit = get_credit(receiver[0],self.main_dic['se_2'],self.main_dic['header_2'])
                new_print(self.fifa_account, 'receiver_credit = ', receiver_credit)
                if receiver_credit < (sniper_lowest_snipe_buy_now_price * 2):
                    new_print(self.fifa_account, 'receiver low credit , change receiver , ',
                              receiver_credit, ' sniper_lowest_snipe_buy_now_price*2 ',
                              sniper_lowest_snipe_buy_now_price*2)
                    self.receiver.error_description = 'receiver no proxy found'
                    self.receiver.has_error = True
                    self.receiver.save(update_fields=['has_error', 'error_description'])
                    return 'change receiver'
                receiver_limit = receiver_credit * 4
                if receiver_limit < 5000:
                    receiver_limit = 5000
                if target_price > receiver_limit:
                    target_price = receiver_limit

                if receiver_credit_counter > 5:
                    new_print(self.fifa_account,
                              ' receiver_credit_counter : ', receiver_credit_counter,
                              ' change receiver ')
                    self.receiver.error_description = 'receiver no proxy found'
                    self.receiver.has_error = True
                    self.receiver.save(update_fields=['has_error', 'error_description'])
                    return 'change receiver'
                if receiver_credit < 550:
                    receiver_credit_counter += 1
                    time.sleep(10)
                    continue

                # sender_limit

                # while True:
                for iie in range(10):
                    try:
                        sender_credit = self.update_credit(
                            self.sender.fifa_account.id, self.main_dic['se_1'], self.main_dic['header_1'])
                        break
                    except:
                        time.sleep(5)
                        new_print(self.fifa_account, 'error 86 : ', traceback.format_exc())
                        self.get_new_sid(self.main_dic['se_1'], self.sender, 'sender')
                # sender_credit = get_credit(sender[0],self.main_dic['se_1'],self.main_dic['header_1'])
                new_print(self.fifa_account, 'sender_credit = ', sender_credit)
                sender_limit = sender_credit - self.sender.transfer_to
                if sender_limit < (sniper_lowest_snipe_buy_now_price * 2):
                    new_print(self.fifa_account, 'sender low credit , change sender , ',
                              sender_credit, ' sniper_lowest_snipe_buy_now_price*2 ',
                              sniper_lowest_snipe_buy_now_price * 2,
                              ' sender limit : ', sender_limit)
                    self.sender.is_done = 1
                    self.sender.save(update_fields=['is_done'])
                    return 'change sender'
                self.sender.refresh_from_db()
                if sender_limit < 4000:
                    new_print(self.fifa_account, 'sender limit : ', sender_limit, ' change sender')
                    self.sender.is_done = True
                    self.sender.save(update_fields=['is_done'])
                    text = 'sender coin is %s %s. will change sender' % (
                        sender_limit, self.sender.fifa_account.user_name)
                    self.sender.is_done = 1
                    self.sender.save(update_fields=['is_done'])
                    self.send_message(bot, 123, text)
                    return 'change sender'
                if target_price > sender_limit:
                    target_price = sender_limit

                # transfer limit

                # while True:
                for iie in range(10):
                    self.receiver.refresh_from_db()
                    if self.receiver.has_error:
                        new_print(self.fifa_account, 'worker has error')
                        return {'status_bool': False, 'text': 'worker has error'}
                    try:
                        receiver_credit_plus = get_credit_web(
                            self.receiver.fifa_account.id, self.main_dic['se_2'], self.main_dic['header_2'],
                            active_trades=True, expire_trades=True).get('plus_credit')
                        break
                    except:
                        time.sleep(5)
                        new_print(self.fifa_account, 'error 87 : ', traceback.format_exc())
                        self.get_new_sid(self.main_dic['se_2'], self.receiver, 'receiver')
                # receiver_credit_plus = get_plus_credit(self.main_dic['se_2'],self.main_dic['header_2'])
                transfer_limit = max_transfer - receiver_credit_plus
                new_print(self.fifa_account, 'transfer_limit = ', transfer_limit)
                if target_price > transfer_limit:
                    target_price = transfer_limit

                if self.sender.empty_size_transfer_limit == 0 and sender_limit < 15000:
                    self.sender.is_done = 1
                    self.sender.save(update_fields=['is_done'])
                    text = 'sender coin is %s %s. will change sender' % (
                        sender_limit, self.sender.fifa_account.user_name)
                    self.send_message(bot, 123, text)
                    return 'change sender'

                if transfer_limit < (sniper_lowest_snipe_buy_now_price * 1.5):
                    self.receiver.is_done = 1
                    self.receiver.save(update_fields=['is_done'])
                    text = 'transfer completed for %s' % self.receiver.fifa_account.user_name
                    self.send_message(bot, 123, text)
                    if self.receiver.need_proof:

                        coins_after = self.receiver.coins_after
                        transfer_amount = self.receiver.transfer_amount
                        coins_taken = self.receiver.coins_taken
                        loop_counter = 0
                        while True:
                            self.receiver.refresh_from_db()
                            if self.receiver.has_error:
                                new_print(self.fifa_account, 'worker has error')
                                return {'status_bool': False, 'text': 'worker has error'}
                            loop_counter += 1
                            self.get_new_sid(self.main_dic['se_2'], self.receiver, 'receiver')

                            while True:
                                self.receiver.refresh_from_db()
                                if self.receiver.has_error:
                                    new_print(self.fifa_account, 'worker has error')
                                    return {'status_bool': False, 'text': 'worker has error'}
                                try:
                                    receiver_credit = self.update_credit(
                                        self.receiver.fifa_account.id, self.main_dic['se_2'], self.main_dic['header_2'])
                                    new_print(
                                        self.fifa_account, 'sniper update credit ,',
                                        ' counter : ', loop_counter)
                                    break
                                except:
                                    time.sleep(5)
                                    new_print(self.fifa_account, 'error 88 : ', traceback.format_exc())
                                    self.get_new_sid(self.main_dic['se_2'], self.receiver, 'receiver')

                            if receiver_credit > coins_after or loop_counter > 5:
                                text = (f'coins used for {transfer_amount} transfer :\n'
                                        f'{coins_taken}\n'
                                        f'#{self.receiver.fifa_account.user_name}\n'
                                        f'loop counter = {loop_counter}')
                                telegram_send_photo(
                                    fifa_account=self.fifa_account,
                                    photo_path=os.path.join(
                                        BASE_DIR, 'sniper/proofs/%s_before.png' % self.receiver.fifa_account.user_name,
                                    ),
                                    caption=text,
                                    message_type='info',
                                    message_thread_id=ARZBAZI_REPORT_TOPIC_GENERAL_THREAD_MESSAGE_ID
                                )
                                # bot.sendPhoto(
                                #     # -1001632841996,
                                #     -1001712554408,
                                #     open(
                                #         os.path.join(
                                #             BASE_DIR,
                                #             'sniper/proofs/%s_after.png' % self.receiver.fifa_account.user_name,
                                #         ),
                                #         'rb'
                                #     ),
                                #     caption='#%s' % self.receiver.fifa_account.user_name)
                                # text = 'coins used for %s transfer :\n%s\n#%s\nloop counter = %s' % \
                                #        (
                                #            transfer_amount, coins_taken, self.receiver.fifa_account.user_name,
                                #            loop_counter)
                                # # bot.sendMessage(-1001632841996, text)
                                # bot.sendMessage(-1001712554408, text)
                                break
                            time.sleep(120)

                    return 'change receiver'

                proxy_ip = self.sender_proxy_ip
                proxy_port = self.sender_proxy_port
                proxy_user = self.sender_proxy_user
                proxy_pass = self.sender_proxy_password
                # if senders_len > receivers_len:
                #     proxy_ip = sender_proxy_ip
                #     proxy_port = sender_proxy_port
                #     proxy_user = sender_proxy_user
                #     proxy_pass = sender_proxy_password
                # else:
                #     proxy_ip = receiver_proxy_ip
                #     proxy_port = receiver_proxy_port
                #     proxy_user = receiver_proxy_user
                #     proxy_pass = receiver_proxy_password

                t_bought = 0
                for page_num in range(1, 5):
                    if t_bought:
                        break
                    last_target_price = target_price
                    if target_price > sniper_highest_target_buy_now_price:
                        target_price = sniper_highest_target_buy_now_price
                    ps_prp = '20,80'
                    # if target_price > 25000:
                    #     ps_prp = '30,80'
                    # if target_price < 10000:
                    #     ps_prp = '10,95'
                    # todo : delete bellow condition
                    # if target_price > 10000:
                    #     target_price = 10000
                    link = f'https://www.futbin.com/players?page={page_num}&ps_price={sniper_lowest_snipe_buy_now_price}-{int(target_price)}&ps_prp={ps_prp}&sort=ps_price&order=desc'

                    resp = self.use_cloud_scraper(link, proxy_ip, proxy_port, proxy_user, proxy_pass).text
                    soup = BeautifulSoup(resp, "html.parser")
                    targets = soup.find_all(class_="player-row")
                    self.sender.refresh_from_db()
                    if not targets:
                        if sender_limit < 4000:
                            text = 'sender coin is %s %s. will change sender' % (
                                sender_limit, self.sender.fifa_account.user_name)
                            self.sender.is_done = 1
                            self.sender.save(update_fields=['is_done'])
                            self.send_message(bot, 123, text)
                            return 'change sender'
                        text = (f'no good target found under {target_price} price in futbin ,'
                                f' account : {self.sender.fifa_account.user_name}')
                        self.send_message(bot, 123, text)
                        return 'need check'
                        # break

                    # special_cards = SniperPlayerCard.objects.filter(
                    #     buy_now_price__lt=last_target_price,
                    #     min_price__lt=receiver_credit,
                    # ).order_by(
                    #     '-buy_now_price'
                    # ).values_list(
                    #     'player_card__asset_id',
                    #     'player_card__futbin_resource_id',
                    #     'player_card__rare',
                    #     'min_price',
                    #     'buy_now_price'
                    # )
                    # todo : uncomment bellow line
                    # targets = list(special_cards) + targets

                    # more than 400000
                    # random_list = [[212198, 67321062,3],[193041, 50524689,3],[189596, 50521244,3]]

                    # more than 300000
                    # random_list = [[230767, 50562415, 21], ]
                    # random_list = [[237692, 50569340, 50], ]
                    # random_target = random.choice(random_list)
                    #
                    # # more than 165000
                    # random_list3 = [[5661, 5661, 72], ]
                    # random_target3 = random.choice(random_list3)
                    #
                    # # more than 80000
                    # random_list2 = [[235243, 50566891, 21], ]
                    # random_target2 = random.choice(random_list2)
                    #
                    # random_target4 = [225793, 50557441, 22]
                    #
                    # random_target5 = [44897, 44897, 72]
                    #
                    # random_target6 = [146536, 50478184, 22]
                    #
                    # random_target7 = [191694, 191694, 72]
                    #
                    # random_target8 = [225193, 50556841, 22]
                    #
                    # random_target9 = [235008, 50566656, 22]
                    #
                    # # todo : fix this special target with dynamic targets # https://trello.com/c/2Ec3PizE/16-%D8%A7%D8%B5%D9%84%D8%A7%D8%AD%DB%8C%D9%87-%D8%AF%D8%B1-%D8%B1%D8%A8%D8%A7%D8%AA-sniper
                    # # if last_target_price > 150000 and receiver_credit > 35000:
                    # #     targets[0:0] = [[51257, 51257, 72], random_target2]
                    # # targets[0:0] = [[51257, 51257, 72]]
                    # # elif last_target_price > 150000:
                    # #     targets[0:0] = [[247614,247614],[167495, 50499143,3]]
                    # # elif last_target_price > 40000 and receiver_credit > 11000:
                    # if last_target_price > 21000 and receiver_credit > 12000:
                    #     targets[0:0] = [random_target9]
                    # if last_target_price > 27000 and receiver_credit > 12000:
                    #     targets[0:0] = [random_target8]
                    # if last_target_price > 30000 and receiver_credit > 10000:
                    #     targets[0:0] = [random_target7]
                    # if last_target_price > 42000 and receiver_credit > 15000:
                    #     targets[0:0] = [random_target4]
                    # if last_target_price > 50000 and receiver_credit > 20000:
                    #     targets[0:0] = [random_target5]
                    # if last_target_price > 60000 and receiver_credit > 15000:
                    #     targets[0:0] = [random_target6]
                    #
                    # if last_target_price > 100000 and receiver_credit > 27000:
                    #     targets[0:0] = [random_target3]
                    # if last_target_price > 200000 and receiver_credit > 28000:
                    #     targets[0:0] = [random_target2]
                    # if last_target_price > 320000 and receiver_credit > 45000:
                    #     targets[0:0] = [random_target]

                    bad_targets_asset_id = []
                    for target in targets:
                        self.receiver.refresh_from_db()
                        if self.receiver.is_done >= 1 or self.receiver.has_error >= 1:
                            return 'manual deactivate'
                        self.check_search_count(self.receiver.fifa_account.id, add_search_count=False)
                        # try:
                        # special_target = 0
                        # rare = 0
                        # try:
                        #     target_asset_part = (target['data-original'])
                        #     target_asset_part = target_asset_part[::-1]
                        #     target_asset_begin = target_asset_part.find('.') + 1
                        #     target_asset_end = target_asset_part.find('/', target_asset_begin)
                        #     target_asset_id = (target_asset_part[target_asset_begin:target_asset_end])[::-1]
                        #     futbin_target_id = target_asset_id
                        # except:
                        #     new_print(self.fifa_account, 'will use special', target)
                        #     target_asset_id = target[0]
                        #     futbin_target_id = target[1]
                        #     try:
                        #         rare = target[2]
                        #     except:
                        #         pass
                        #     special_target = target
                        futbin_target_id = re.search(r'player/(\d+)/', target.find('td').find('a').get('href')).group(1)
                        player_futbin_info = self.get_data_from_furbin_with_target_information(futbin_id=futbin_target_id)
                        rare = player_futbin_info.get('rare_id')
                        target_asset_id = player_futbin_info.get('asset_id')
                        futbin_player_price = player_futbin_info.get('price')
                        # futbin_player_price = player_futbin_info.get('first_price')
                        if not futbin_player_price:
                            new_print(self.fifa_account, 'player has not price , futbin id : ', futbin_target_id,
                                      ' futbin info : ', player_futbin_info, ' , continue.')
                            continue
                        player_update_time_stamp = player_futbin_info.get('update_time_stamp')
                        if player_update_time_stamp and player_update_time_stamp > (time.time() - 600):
                            pass
                        else:
                            new_print(self.fifa_account,
                                      'update time is more than 10 minute ago , try another',
                                      ' player id : ', futbin_target_id,
                                      ' update time : ', player_futbin_info.get('update_time'),
                                      ' update time_stamp : ', player_update_time_stamp, ' , continue.')
                            continue
                        min_price = player_futbin_info.get('futbin_min_price')
                        min_price = int(str(min_price).replace(',', ''))
                        g_n_p_g = get_next_price_grade
                        if g_n_p_g(g_n_p_g(min_price)) > receiver_credit:
                            new_print(self.fifa_account, 'get_next_price_grade(min_price) > receiver_credit',
                                      g_n_p_g(g_n_p_g(min_price)), receiver_credit, ' , continue.')
                            continue
                        player_price_list = player_futbin_info.get('futbin_price_list')
                        if player_price_list and player_price_list[-1] in ['0', 0]:
                            new_print(self.fifa_account, 'futbin price is not certain, continue.')
                            continue
                        upgraded_first_step_price = int(player_price_list[0].replace(',', ''))
                        step_two_price = int(player_price_list[1].replace(',', ''))
                        for iiee in range(2):
                            upgraded_first_step_price = g_n_p_g(int(player_price_list[0].replace(',', '')))
                        if upgraded_first_step_price < step_two_price:
                            new_print(self.fifa_account,
                                      'player upgraded_first_step_price is less than step two price ',
                                      upgraded_first_step_price, ' -- ', step_two_price, ' , continue.')
                            continue

                        target_player_card = PlayerCard.objects.filter(asset_id=target_asset_id, rare=rare).first()

                        if target_player_card:
                            target_cards = SniperTradeItemLog.objects.filter(
                                player_card=target_player_card
                            ).exclude(
                                buy_now_price=F('price')
                            )
                            last_missed_count = target_cards.filter(
                                action_time__gte=timezone.localtime() - timezone.timedelta(seconds=60 * 60),
                                status=0,
                            ).count()
                            if last_missed_count >= 1:
                                bad_targets_asset_id.append(target_asset_id)
                                new_print(self.fifa_account,
                                          f'card {target_asset_id} has more than 1 missed in last hour',
                                          ' automatic change card for snip'
                                          )
                                continue
                            missed_count = target_cards.filter(
                                action_time__gte=timezone.localtime() - timezone.timedelta(hours=48),
                                status=0
                            ).count()
                            success_count_1 = target_cards.filter(
                                action_time__gte=timezone.localtime() - timezone.timedelta(hours=48),
                                status=1
                            ).count()
                            if success_count_1 and (missed_count / success_count_1) > .3:
                                bad_targets_asset_id.append(target_asset_id)
                                new_print(self.fifa_account,
                                          f'card {target_asset_id} has {missed_count / success_count_1} miss rate',
                                          ' automatic change card for snip'
                                          )
                                continue
                        else:
                            new_print(self.fifa_account,
                                      'can not find player card , asset id : ', target_asset_id, 'rare : ', rare)
                        # resp = self.use_cloud_scraper(
                        #     'https://www.futbin.com/24/playerPrices?player=%s' % futbin_target_id,
                        #     proxy_ip, proxy_port, proxy_user, proxy_pass)
                        # json_resp = json.loads(resp)
                        # futbin_prices = json_resp[str(futbin_target_id)]['prices']['ps']
                        #

                        # futbin_all_prices_list = []
                        # if futbin_prices.get('LCPrice', "0") != "0":
                        #     futbin_all_prices_list.append(futbin_prices.get('LCPrice', "0"))
                        # if futbin_prices.get('LCPrice2', "0") != "0":
                        #     futbin_all_prices_list.append(futbin_prices.get('LCPrice2', "0"))
                        # if futbin_prices.get('LCPrice3', "0") != "0":
                        #     futbin_all_prices_list.append(futbin_prices.get('LCPrice3', "0"))
                        # if futbin_prices.get('LCPrice4', "0") != "0":
                        #     futbin_all_prices_list.append(futbin_prices.get('LCPrice4', "0"))
                        # if futbin_prices.get('LCPrice5', "0") != "0":
                        #     futbin_all_prices_list.append(futbin_prices.get('LCPrice5', "0"))
                        # new_print(self.fifa_account, 'futbin_all_prices_list = ', futbin_all_prices_list)
                        #
                        # if (not special_target) and str(futbin_prices.get('LCPrice4', "0")) == "0":
                        #     new_print(self.fifa_account, 'futbin price is not certain')
                        #     continue
                        #
                        # if len(futbin_all_prices_list) == 0:
                        #     futbin_all_prices_list = ["0"]

                        # player_found = 5
                        # if special_target:
                        #     futbin_player_price = futbin_prices.get('LCPrice3', "0")
                        #     if futbin_player_price == '0':
                        #         continue
                        #     player_found = 3
                        # else:
                        #     futbin_player_price = most_common(futbin_all_prices_list)
                        # futbin_player_price = int(futbin_player_price.replace(',', ''))
                        # futbin_price_update_time = json_resp[str(futbin_target_id)]['prices']['ps']['updated']
                        # new_print(self.fifa_account, 'futbin_player_price = ', futbin_player_price,
                        #           futbin_price_update_time)
                        player_price = player_futbin_info.get('futbin_price_list', [])[0]
                        player_first_price = player_futbin_info.get('first_price')
                        player_min_price = player_futbin_info.get('futbin_min_price')
                        # unstable = 0
                        # if futbin_player_price > 100000:
                        #     change_grade = 6
                        # else:
                        #     change_grade = 4
                        # if special_target:
                        #     change_grade = 20
                        # while True:
                        #     self.receiver.refresh_from_db()
                        #     # if self.receiver.is_done >= 1 or self.receiver.has_error >= 1:
                        #     #     return 'manual deactivate'
                        #     self.sender.fifa_account.refresh_from_db()
                        #     self.sender.refresh_from_db()
                        #     if self.sender.fifa_account.account_search.filter(
                        #             search_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                        #     ).count() >= self.account_high_search_count:
                        #         self.sender.error_description = 'high search'
                        #         self.sender.has_error = True
                        #         self.sender.save(update_fields=['has_error', 'error_description'])
                        #         text = 'sender max search limit %s. will change sender' % (
                        #             self.sender.fifa_account.user_name)
                        #         self.sender.is_done = 1
                        #         self.sender.save(update_fields=['is_done'])
                        #         self.send_message(bot, 123, text)
                        #         return 'change sender'
                        #     try:
                        #         player_price = self.search_price(
                        #             self.main_dic['se_1'],
                        #             self.main_dic['header_1'],
                        #             self.main_dic['persona_id_1'],
                        #             self.main_dic['nucleus_id_1'],
                        #             self.sender_proxy_ip, self.sender_proxy_port,
                        #             self.sender_proxy_user, self.sender_proxy_password,
                        #             futbin_player_price, target_asset_id,
                        #             trade_mode=3, change_grade=change_grade,
                        #             force_manual=1, account_id=self.sender.fifa_account.id,
                        #             player_found=player_found, rare=rare)
                        #
                        #         if str(player_price) == 'unstable':
                        #             unstable = 1
                        #             break
                        #         new_print(self.fifa_account, 'player price = ', int(player_price))
                        #         break
                        #     except:
                        #         time.sleep(5)
                        #         new_print(self.fifa_account, 'error 89 : ', traceback.format_exc())
                        #         self.get_new_sid(self.main_dic['se_1'], self.sender, 'sender')
                        # if unstable:
                        #     new_print(self.fifa_account, 'player price is unstable')
                        #     continue

                        if get_next_price_grade(player_price) > sender_limit:
                            new_print(self.fifa_account, 'sender limit is less than player price')
                            continue

                        # if get_previous_price_grade(get_previous_price_grade(get_previous_price_grade(futbin_player_price))) <= player_price <= get_next_price_grade(get_next_price_grade(get_next_price_grade(futbin_player_price))):
                        #     pass
                        # else:
                        #     print 'player price is unstable 2'
                        #     continue

                        # player_price = search_price(main_dic['se_1'], main_dic['header_1'], main_dic['persona_id_1'],
                        #                             main_dic['nucleus_id_1'],
                        #                             account_1[3], account_1[4], futbin_player_price, target_asset_id, trade_mode=3,
                        #                             force_manual=1)
                        # print 'player price = ', int(player_price)

                        # check minimum price number of players
                        # if futbin_player_price > 100000:
                        #     player_price = get_previous_price_grade(get_previous_price_grade(get_previous_price_grade(player_price)))
                        # time.sleep(1.5)
                        # while True:
                        #     try:
                        #         resp = search_player(main_dic['se_1'], main_dic['header_1'], main_dic['persona_id_1'],
                        #                              main_dic['nucleus_id_1'],
                        #                              target_asset_id, get_previous_price_grade(player_price), 'max_buy'
                        #                              ,account_id = account_1[6])
                        #         json_resp = resp.json()
                        #         break
                        #     except:
                        #         time.sleep(5)
                        #         print traceback.format_exc()
                        #         get_new_sid(main_dic['se_1'], account_1, 'sender')
                        # auction_info = json_resp['auctionInfo']
                        # if len(auction_info) > 1:
                        #     print 'player price is not certain'
                        #     continue

                        # if futbin_player_price < 40000:
                        #     time.sleep(1.5)
                        #     while True:
                        #         self.receiver.refresh_from_db()
                        #         if self.receiver.is_done >= 1 or self.receiver.has_error >= 1:
                        #             return 'manual deactivate'
                        #         self.sender.refresh_from_db()
                        #         self.sender.fifa_account.refresh_from_db()
                        #         if self.sender.fifa_account.account_search.filter(
                        #             search_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                        #         ).count() >= self.account_high_search_count:
                        #             self.sender.error_description = 'high search'
                        #             self.sender.has_error = True
                        #             self.sender.save(update_fields=['has_error', 'error_description'])
                        #             text = 'sender max search limit %s. will change sender' % (
                        #                 self.sender.fifa_account.user_name)
                        #             self.sender.is_done = 1
                        #             self.sender.save(update_fields=['is_done'])
                        #             self.send_message(bot, 123, text)
                        #             return 'change sender'
                        #         try:
                        #             resp = self.search_player(
                        #                 self.main_dic['se_1'], self.main_dic['header_1'], self.main_dic['persona_id_1'],
                        #                 self.main_dic['nucleus_id_1'], target_asset_id, get_next_price_grade(
                        #                     get_next_price_grade(
                        #                         get_next_price_grade(get_next_price_grade(player_price)))),
                        #                 'max_buy', account_id=self.sender.fifa_account.id, rare=rare)
                        #             json_resp = resp.json()
                        #             break
                        #         except:
                        #             time.sleep(5)
                        #             new_print(self.fifa_account, 'error 83 : ', traceback.format_exc())
                        #             self.get_new_sid(self.main_dic['se_1'], self.sender, 'sender')
                        #     auction_info = json_resp.get('auctionInfo', [])
                        #     if len(auction_info) < 20:
                        #         new_print(self.fifa_account, 'player price is not certain')
                        #         continue
                        #     time.sleep(1)

                        # if futbin_player_price > 100000:
                        #     player_price = get_next_price_grade(get_next_price_grade(get_next_price_grade(player_price)))

                        # if not self.main_dic['first_bid']:
                        #     print 'first bid staff'
                        #     new_se = requests.session()
                        #     while True:
                        #         try:
                        #             resp = search_player(new_se, self.main_dic['header_2'],
                        #                                  main_dic['persona_id_2'],
                        #                                  main_dic['nucleus_id_2'],
                        #                                  target_asset_id, get_next_price_grade(player_price), 'max_buy')
                        #             json_resp = resp.json()
                        #             new_print(self.fifa_account,'fake search time = ', resp.elapsed.total_seconds())
                        #             break
                        #         except:
                        #             time.sleep(5)
                        #             print traceback.format_exc()
                        #             get_new_sid(main_dic['se_2'], account_2, 'receiver')
                        #     fake_auction_info = json_resp['auctionInfo']
                        #     fake_bid = 0
                        #     for fake_target in fake_auction_info:
                        #         if fake_target['currentBid']:
                        #             data = '{"bid":%d}' % fake_target['currentBid']
                        #             bid_resp = bid_trade(new_se, main_dic['header_2'], fake_target['tradeId'], data)
                        #             print 'fake bid resp =',bid_resp.content
                        #             new_print(self.fifa_account,'fake bid time = ', bid_resp.elapsed.total_seconds())
                        #             time.sleep(5)
                        #             fake_bid = 1
                        #             break
                        #     if not fake_bid:
                        #         print 'couldnt do a fake bid on this target'
                        #         continue
                        #     main_dic['first_bid'] = 1

                        new_print(self.fifa_account, 'this player selected for sniper , ', player_futbin_info)
                        while True:
                            self.receiver.refresh_from_db()
                            if self.receiver.is_done >= 1 or self.receiver.has_error >= 1:
                                return 'manual deactivate'
                            self.sender.refresh_from_db()
                            self.sender.fifa_account.refresh_from_db()
                            if self.sender.fifa_account.account_search.filter(
                                    search_time__gt=timezone.localtime() - timezone.timedelta(hours=24)
                            ).count() >= self.account_high_search_count:
                                self.sender.error_description = 'high search'
                                self.sender.has_error = True
                                self.sender.save(update_fields=['has_error', 'error_description'])
                                text = 'sender max search limit %s. will change sender' % (
                                    self.sender.fifa_account.user_name)
                                self.sender.is_done = 1
                                self.sender.save(update_fields=['is_done'])
                                self.send_message(bot, 123, text)
                                return 'change sender'
                            try:
                                resp = self.search_player(
                                    self.main_dic['se_1'], self.main_dic['header_1'], self.main_dic['persona_id_1'],
                                    self.main_dic['nucleus_id_1'], target_asset_id,
                                    get_next_price_grade(player_price), 'max_buy',
                                    account_id=self.sender.fifa_account.id, rare=rare)
                                new_print(self.fifa_account, 'search time =', resp.elapsed.total_seconds())
                                json_resp = resp.json()
                                break
                            except:
                                time.sleep(5)
                                new_print(self.fifa_account, 'error 82 : ', traceback.format_exc())
                                self.get_new_sid(self.main_dic['se_1'], self.sender, 'sender')
                        # resp = search_player(main_dic['se_1'], main_dic['header_1'], main_dic['persona_id_1'],
                        #                      main_dic['nucleus_id_1'],
                        #                      target_asset_id, get_next_price_grade(player_price), 'max_buy')
                        # json_resp = resp.json()
                        auction_info = json_resp['auctionInfo']
                        auction_info = [item for item in auction_info if int(item['itemData'].get('rating')) == int(player_futbin_info.get('player_rating') or 0)]
                        auction_info = sorted(auction_info, key=lambda x: x.get('buyNowPrice', float('inf')))
                        bought_item_id = 0

                        for player in auction_info:

                            data = json.dumps({"bid": player['buyNowPrice']})
                            check_resp = self.check_trade(self.main_dic['se_1'], self.main_dic['header_1'],
                                                          player['tradeId'])
                            check_resp_json = check_resp.json()
                            if check_resp_json['auctionInfo'][0]['tradeState'] != 'active':
                                new_print(self.fifa_account, 'trade is closed')
                                time.sleep(0.5)
                                continue
                            bid_resp = self.bid_trade(self.main_dic['se_1'], self.main_dic['header_1'],
                                                      player['tradeId'], data)

                            if (bid_resp.text == 'Permission Denied' or
                                    bid_resp.text == '' or
                                    bid_resp.text == 'You are not allowed to bid on this trade' or
                                    bid_resp.text.find('expired session') != -1):
                                time.sleep(1.5)
                                continue
                            else:
                                bought_item_id = player['itemData']['id']
                                this_tax = (get_next_price_grade(min_price) * 5) / 100
                                this_coins_taken = player['buyNowPrice'] - get_next_price_grade(
                                    min_price) + this_tax
                                self.receiver.refresh_from_db()
                                self.receiver.coins_taken += this_coins_taken
                                self.receiver.save()
                                # if special_target:
                                #     if player['buyNowPrice'] < (player_price - ((player_price * 5) / 100)):
                                #         player_price = get_round_top_price(
                                #             player_price - ((player_price * 5) / 100))
                                #         # player_price = get_previous_price_grade(player_price)
                                #     else:
                                #         player_price = player['buyNowPrice']
                                player_price = player['buyNowPrice']
                                new_print(self.fifa_account, 'bought price = ', player['buyNowPrice'])

                            break
                        if bought_item_id:
                            new_print(self.fifa_account, 'item_id = ', bought_item_id)
                            if third_account:
                                while True:
                                    # resp = self.check_trade(self.main_dic['se_3'], self.main_dic['header_3'],
                                    #                         fake_trade_id)
                                    resp = self.main_dic['se_3'].get(
                                        f'{fifa_23_address}/tradepile')
                                    try:
                                        new_print(self.fifa_account, 'check trade time = ',
                                                  resp.elapsed.total_seconds())
                                        resp.json()
                                        break
                                    except:
                                        time.sleep(5)
                                        new_print(self.fifa_account, 'third driver session expired')
                                        # self.get_new_sid(self.main_dic['se_3'], account_3, 'third')

                            second_driver_checker_counter = 0
                            while True:
                                self.receiver.refresh_from_db()
                                if self.receiver.is_done >= 1 or self.receiver.has_error >= 1:
                                    return 'manual deactivate'
                                second_driver_checker_counter += 1
                                if second_driver_checker_counter > 2:
                                    text = 'user is online %s' % self.receiver.fifa_account.user_name
                                    self.send_message(bot, 123, text)
                                    self.receiver.error_description = "user is online"
                                    self.receiver.has_error = True
                                    self.receiver.save(update_fields=['has_error', 'error_description'])
                                    return 'change receiver'
                                # resp = self.check_trade(self.main_dic['se_2'], self.main_dic['header_2'],
                                #                         fake_trade_id)
                                resp = self.main_dic['se_2'].get(
                                    f'{fifa_23_address}/tradepile')
                                try:
                                    new_print(self.fifa_account, 'check trade time = ', resp.elapsed.total_seconds())
                                    resp.json()
                                    break
                                except:
                                    time.sleep(5)
                                    new_print(self.fifa_account, 'second driver session expired 2 ', traceback.format_exc())
                                    self.get_new_sid(self.main_dic['se_2'], self.receiver, 'receiver')

                            new_print(self.fifa_account, 'second driver session is ok')
                            # new_price = get_round_top_price(player_price / 2)
                            # new_price = get_previous_price_grade(get_previous_price_grade(get_previous_price_grade(player_price)))
                            # new_price = 1500
                            link = f'{fifa_23_address}/marketdata/item/pricelimits?itemIdList={bought_item_id}'
                            resp = self.main_dic['se_1'].get(link, headers=self.main_dic['header_1'])
                            new_print(self.fifa_account, link)
                            new_print(self.fifa_account, 'resp = ', resp.text)
                            js_resp = resp.json()
                            min_price = js_resp[0]['minPrice']
                            # if min_price < 50000 and target_price > 60000:
                            #     min_price = 50000
                            if min_price < sniper_lowest_snipe_buy_now_price:
                                min_price = sniper_lowest_snipe_buy_now_price
                            new_price = get_next_price_grade(int(min_price))
                            time.sleep(2)
                            # new_price = get_previous_price_grade(player_price)
                            # todo : some codes need check here
                            start_price = get_previous_price_grade(new_price)
                            buy_now_price = new_price
                            # a = time.time()

                            # Start Core ...
                            trade_id = 0
                            self.reverse_catcher = False
                            for nm in range(10):
                                if self.reverse_catcher is False:
                                    catcher_worker_key = 3
                                    sender_worker_key = 1
                                else:
                                    catcher_worker_key = 1
                                    sender_worker_key = 3
                                while True:
                                    try:
                                        resp = self.item_put_for_sale(
                                            self.main_dic[f'se_{sender_worker_key}'],
                                            self.main_dic[f'header_{sender_worker_key}'], bought_item_id,
                                            auction_info[-1]['tradeId'], 0,
                                            worker_key=sender_worker_key,
                                            start_price=start_price,
                                            buy_now_price=buy_now_price, target_asset_id=target_asset_id,
                                            test_sniper=0)
                                        put_for_sale_resp = resp
                                        json_resp = resp.json()
                                        trade_id = json_resp['id']
                                        break
                                    except:
                                        time.sleep(5)
                                        new_print(self.fifa_account, 'first driver session expired')
                                        if self.reverse_catcher is False:
                                            self.get_new_sid(self.main_dic[f'se_1'], self.sender, 'sender')
                                        else:
                                            self.get_new_sid(self.main_dic[f'se_3'], self.catcher, 'catcher')

                                        new_print(self.fifa_account, 'third and second driver check again')
                                        # while True:
                                        #     resp = check_trade(main_dic['se_3'], main_dic['header_3'], fake_trade_id)
                                        #     try:
                                        #         new_print(self.fifa_account,'check trade time = ', resp.elapsed.total_seconds())
                                        #         resp.json()
                                        #         break
                                        #     except:
                                        #         time.sleep(5)
                                        #         print 'third driver session expired'
                                        #         get_new_sid(main_dic['se_3'], account_3, 'third')

                                        while True:
                                            self.receiver.refresh_from_db()
                                            if self.receiver.is_done == 1 or self.receiver.has_error == 1:
                                                return 'manual deactivate'
                                            # resp = self.check_trade(self.main_dic['se_2'],
                                            #                         self.main_dic['header_2'], fake_trade_id)
                                            resp = self.main_dic['se_2'].get(
                                                f'{fifa_23_address}/user/credits')
                                            try:
                                                new_print(self.fifa_account, 'check trade time = ',
                                                          resp.elapsed.total_seconds())
                                                resp.json()
                                                break
                                            except:
                                                time.sleep(5)
                                                new_print(self.fifa_account, 'second driver session expired 3 , ', traceback.format_exc())
                                                self.get_new_sid(self.main_dic['se_2'], self.receiver, 'receiver')

                                # new_print(self.fifa_account,'put for sale time = ',resp.elapsed.total_seconds())
                                # b = time.time()

                                # threading.Thread(target=search_before_bid,
                                #                  kwargs={'buy_now_price': buy_now_price, 'target_asset_id': target_asset_id,
                                #                          'trade_id':trade_id}).start()
                                # time.sleep(0.01)
                                # search_resp = self.search_before_bid(buy_now_price, target_asset_id, trade_id, rare)
                                # time.sleep(0.1)
                                search_receiver_resp, aaa = self.search_before_bid(
                                    worker_key=2, buy_now_price=buy_now_price,
                                    target_asset_id=target_asset_id,
                                    trade_id=trade_id, rare=rare
                                )
                                # search_receiver = ThreadWithReturnValue(
                                #     target=self.search_before_bid,
                                #     kwargs={'worker_key': 2, 'buy_now_price': buy_now_price,
                                #             'target_asset_id': target_asset_id,
                                #             'trade_id': trade_id, 'rare': rare})
                                # search_receiver.start()
                                if self.catcher:
                                    # start catcher requests
                                    search_catcher = ThreadWithReturnValue(
                                        target=self.search_before_bid,
                                        kwargs={'worker_key': catcher_worker_key, 'buy_now_price': buy_now_price,
                                                'target_asset_id': target_asset_id,
                                                'trade_id': trade_id, 'rare': rare, 'bid_after_search': True})
                                    search_catcher.start()
                                # if found:

                                # break_search_alive = False
                                # for nt in range(5):
                                #     if search_receiver.is_alive():
                                #         time.sleep(.007)
                                #         continue
                                #     break_search_alive = True
                                #     break
                                # این عدد برای تاخیر ارسال خرید بعد از سرچ اضافه شده و در جواب 0.025 بوده است
                                # time.sleep(0.015)
                                # time.sleep(0.07)
                                bid_receiver_data = json.dumps({"bid": new_price})
                                # delay_end = time.time()
                                # print 'delay time = ',delay_end - delay_start
                                # c = time.time()
                                # new_se = requests.session()
                                bid_resp = self.bid_trade(
                                    se=self.main_dic['se_2'], header=self.main_dic['header_2'],
                                    trade_id=trade_id, data=bid_receiver_data, safe=0
                                )
                                # bid_receiver = ThreadWithReturnValue(target=self.bid_trade, kwargs={
                                #     'se': self.main_dic['se_2'], 'header': self.main_dic['header_2'],
                                #     'trade_id': trade_id, 'data': data, 'safe': 0,
                                # })
                                # bid_receiver.start()
                                # bid_resp = self.bid_trade(self.main_dic['se_2'], self.main_dic['header_2'],
                                #                           trade_id, data, safe=0)

                                if self.catcher:
                                    # start catcher requests
                                    # search_catcher = ThreadWithReturnValue(
                                    #     target=self.search_before_bid,
                                    #     kwargs={'worker_key': '3', 'buy_now_price': buy_now_price,
                                    #             'target_asset_id': target_asset_id,
                                    #             'trade_id': trade_id})
                                    # search_catcher.start()
                                    # time.sleep(0.01)
                                    search_catcher_resp, bid_catcher_resp = search_catcher.join()
                                    # bid_catcher = ThreadWithReturnValue(target=self.bid_trade, kwargs={
                                    #     'se': self.main_dic['se_3'], 'header': self.main_dic['header_3'],
                                    #     'trade_id': trade_id, 'data': data, 'safe': 0,
                                    # })
                                    # bid_catcher.start()
                                    # search_catcher_resp = search_catcher.join()
                                    # bid_catcher_resp = bid_catcher.join()
                                    new_print(self.fifa_account, 'search catcher : elapse = ',
                                              search_catcher_resp.elapsed.total_seconds(),
                                              ' resp text = ', search_catcher_resp.text
                                              )
                                    if bid_catcher_resp:
                                        new_print(self.fifa_account, 'bid catcher : elapse = ',
                                                  bid_catcher_resp.elapsed.total_seconds(),
                                                  ' resp text = ', bid_catcher_resp.text
                                                  )

                                    # end catcher requests
                                new_print(self.fifa_account, 'put_for_sale_resp time = ',
                                          put_for_sale_resp.elapsed.total_seconds())
                                # search_receiver_resp, aaa = search_receiver.join()
                                # bid_resp = bid_receiver.join()
                                new_print(self.fifa_account, 'search receiver : elapse = ',
                                          search_receiver_resp.elapsed.total_seconds(),
                                          # ' break search : ', break_search_alive,
                                          ' resp text = ', search_receiver_resp.text
                                          )
                                new_print(self.fifa_account, 'bid receiver : elapse = ',
                                          bid_resp.elapsed.total_seconds(),
                                          ' resp text = ', bid_resp.text,
                                          ' data = ', bid_receiver_data,
                                          ' trade id = ', trade_id
                                          )
                                FifaAccountSearch.objects.create(fifa_account_id=self.receiver.fifa_account.id,
                                                                 search_time=timezone.localtime())
                                if self.catcher:
                                    if (bid_resp.text in ['Permission Denied', '',
                                                          'You are not allowed to bid on this trade'] or
                                        bid_resp.text.find('expired session') != -1) and (
                                            bid_catcher_resp.text in ['Permission Denied', '',
                                                                      'You are not allowed to bid on this trade'] or
                                            bid_catcher_resp.text.find('expired session') != -1
                                    ):
                                        new_print(self.fifa_account, 'bad miss. catcher and receiver miss')
                                        break

                                    elif (bid_resp.text in ['Permission Denied', '',
                                                            'You are not allowed to bid on this trade'] or
                                          bid_resp.text.find('expired session') != -1):
                                        new_print(self.fifa_account,
                                                  'receiver not got it. try to change sender and catcher')
                                        SniperTradeItemLog.objects.create(
                                            sniper_order=self.receiver.sniper_order,
                                            sniper_account_id=self.receiver.id,
                                            player_card=target_player_card,
                                            action_time=timezone.localtime(),
                                            buy_now_price=buy_now_price,
                                            price=buy_now_price,
                                            status=0,
                                        )
                                        time.sleep(10)
                                        self.reverse_catcher = not self.reverse_catcher
                                        continue
                                    else:
                                        break
                                else:
                                    break
                                # for num in range(3):
                                #     if (bid_resp.text in ['Permission Denied', '',
                                #                           'You are not allowed to bid on this trade']):
                                #         # one more try
                                #         search_resp = self.search_before_bid(
                                #             buy_now_price, target_asset_id, trade_id, rare)
                                #         try:
                                #             search_json = search_resp.json()
                                #             if not search_json["auctionInfo"]:
                                #                 new_print(self.fifa_account, 'one more try . search : ',
                                #                           search_json, 'try again')
                                #                 continue
                                #             if search_json['auctionInfo'][0]['expires'] == -1:
                                #                 new_print(self.fifa_account, 'one more try . search : ',
                                #                           search_json['auctionInfo'], 'item expired')
                                #                 break
                                #         except:
                                #             pass
                                #         bid_resp = self.bid_trade(self.main_dic['se_2'], self.main_dic['header_2'],
                                #                                   trade_id, data, safe=1)
                                #         new_print(self.fifa_account, 'one more try . search : ', search_resp.text)
                                #         new_print(self.fifa_account, 'one more try . bid resp : ', bid_resp.text)
                                #         new_print(self.fifa_account, 'check_trade in loop = ',
                                #                   self.check_trade(self.main_dic['se_2'], self.main_dic['header_2'],
                                #                                    trade_id).text)
                                #     else:
                                #         new_print(self.fifa_account, 'can not read bid resp : ', bid_resp.text)
                                #         break
                                # try:
                                #     founded_auction_info = search_resp.json().get('auctionInfo', [])
                                #     for trade in founded_auction_info:
                                #         if trade['tradeId'] != trade_id:
                                #             bid_resp2 = self.bid_trade(
                                #                 self.main_dic['se_2'], self.main_dic['header_2'],
                                #                 trade['tradeId'], data, safe=0)
                                #             new_print(self.fifa_account, 'other players bid response : ',
                                #                       bid_resp2.text)
                                #             new_print(self.fifa_account, 'find other players in search : ', trade)
                                #             self.send_message(
                                #                 bot, 123,
                                #                 f'find other players in search : price {buy_now_price}, '
                                #                 f'asset id {target_asset_id} , {self.fifa_account.user_name}')
                                # except:
                                #     new_print(self.fifa_account, 'find other error : ', traceback.format_exc())
                            if True:
                                if (bid_resp.text in ['Permission Denied', '',
                                                      'You are not allowed to bid on this trade'] or
                                        bid_resp.text.find('expired session') != -1):
                                    # if third_account:
                                    #     threading.Thread(target=self.third_account_search,
                                    #                      kwargs={'buy_now_price': buy_now_price,
                                    #                              'target_asset_id': target_asset_id,
                                    #                              'rare': rare}).start()
                                    #     # time.sleep(0.007)
                                    #     bid_resp_sp = self.bid_trade(self.main_dic['se_3'], self.main_dic['header_3'],
                                    #                                  trade_id, data,
                                    #                                  safe=0)
                                    #     new_print(self.fifa_account, bid_resp_sp.text)
                                    new_print(self.fifa_account, 'missed this one')
                                    SniperTradeItemLog.objects.create(
                                        sniper_order=self.receiver.sniper_order,
                                        sniper_account_id=self.receiver.id,
                                        player_card=target_player_card,
                                        action_time=timezone.localtime(),
                                        buy_now_price=buy_now_price,
                                        price=player_price,
                                        status=0,
                                    )

                                    new_print(self.fifa_account, 'check_trade = ', (
                                        self.check_trade(self.main_dic['se_2'], self.main_dic['header_2'],
                                                         trade_id)).text)
                                    t_bought = 1
                                    text = f'missed item.asset id : {target_asset_id} ' \
                                           f'buy_now_price {buy_now_price} missed_price = {player_price} , ' \
                                           f'fifa account : {self.fifa_account.user_name}'
                                    self.send_message(bot, 123, text)
                                    # if third_account:
                                    #     if (bid_resp_sp.text == 'Permission Denied' or
                                    #             bid_resp_sp.text == '' or
                                    #             bid_resp_sp.text == 'You are not allowed to bid on this trade' or
                                    #             bid_resp.text.find('expired session') != -1):
                                    #         pass
                                    #     else:
                                    #         text = 'the third account saved it. item price = %s' % player_price
                                    #         self.send_message(bot, 123, text)
                                    #         while True:
                                    #             try:
                                    #                 json_bid_resp = bid_resp_sp.json()
                                    #                 player_club_id = json_bid_resp['auctionInfo'][0]['itemData']['id']
                                    #                 player_price = get_previous_price_grade(player_price)
                                    #                 if futbin_player_price > 100000:
                                    #                     player_price = get_previous_price_grade(
                                    #                         get_previous_price_grade(
                                    #                             get_previous_price_grade(player_price)))
                                    #                 resp = self.item_put_for_sale(
                                    #                     self.main_dic['se_3'], self.main_dic['header_3'],
                                    #                     player_club_id, json_bid_resp['auctionInfo'][0]['tradeId'], 0,
                                    #                     start_price=get_previous_price_grade(
                                    #                         get_previous_price_grade(player_price)),
                                    #                     buy_now_price=get_previous_price_grade(player_price))
                                    #                 new_print(self.fifa_account, resp.json())
                                    #                 if special_target:
                                    #                     time.sleep(30)
                                    #                 break
                                    #             except:
                                    #                 new_print(self.fifa_account, traceback.format_exc())
                                    #                 time.sleep(5)
                                    #                 new_print(self.fifa_account, 'third driver session expired')
                                    #                 # self.get_new_sid(self.main_dic['se_3'], account_3, 'third')
                                    if player_price > 40000:
                                        time.sleep(15)
                                    time.sleep(5)
                                    break
                                else:
                                    success_count += 1
                                    new_print(self.fifa_account, 'transfer completed')
                                    sniper_trade_item = SniperTradeItemLog.objects.create(
                                        sniper_order=self.receiver.sniper_order,
                                        sniper_account_id=self.receiver.id,
                                        player_card=target_player_card,
                                        action_time=timezone.localtime(),
                                        buy_now_price=buy_now_price,
                                        price=player_price,
                                        status=1,
                                    )
                                    json_bid_resp = bid_resp.json()
                                    player_club_id = json_bid_resp['auctionInfo'][0]['itemData']['id']
                                    # resp = item_put_for_sale(main_dic['se_2'], main_dic['header_2'], player_club_id,
                                    #                          json_bid_resp['auctionInfo'][0]['tradeId'], 0, start_price=get_previous_price_grade(player_price),
                                    #                          buy_now_price=player_price)

                                    # player_price = get_previous_price_grade(player_price)
                                    sell_player_price = player_first_price
                                    gppg = get_previous_price_grade
                                    if sell_player_price > 100000:
                                        sell_player_price = gppg(gppg(gppg(sell_player_price)))
                                    elif sell_player_price > 50000:
                                        sell_player_price = gppg(gppg(sell_player_price))

                                    if receiver_credit < (buy_now_price * 4):
                                        sell_player_price = gppg(sell_player_price)

                                    while True:
                                        try:
                                            sell_start_price = gppg(gppg(gppg(gppg(gppg(sell_player_price)))))
                                            if sell_start_price < int(player_min_price or 0):
                                                sell_start_price = int(player_min_price)
                                            resp = self.item_put_for_sale(
                                                self.main_dic['se_2'], self.main_dic['header_2'], player_club_id,
                                                json_bid_resp['auctionInfo'][0]['tradeId'], 0,
                                                worker_key=2,
                                                start_price=sell_start_price,
                                                buy_now_price=sell_player_price)
                                            new_print(self.fifa_account,
                                                      'put item for sale resp 1 : ', resp.json(),
                                                      ' sell start price : ', sell_start_price,
                                                      ' sell buy now price : ', sell_player_price)
                                            sniper_trade_item.sell_price = sell_player_price
                                            sniper_trade_item.save()
                                            break
                                        except:
                                            time.sleep(5)
                                            new_print(self.fifa_account, 'second driver session expired 4 ', traceback.format_exc())
                                            self.get_new_sid(self.main_dic['se_2'], self.receiver, 'receiver')

                                    new_print(self.fifa_account, 'success count = ', success_count)
                                    time.sleep(5)
                                    self.main_dic['fail_number'] = 0
                                    delete_sold_items(self.main_dic['se_2'], self.main_dic['header_2'], self.server_key)
                                    delete_sold_items(self.main_dic['se_1'], self.main_dic['header_1'], self.server_key)
                                    t_bought = 1
                                    break
                                # print get_credit(account_1[0], main_dic['se_1'], main_dic['header_1'])
                                # print get_credit(account_2[0], main_dic['se_2'], main_dic['header_2'])
                            # End Core
                            # else:
                            #     new_print(self.fifa_account, 'trade not found')
                            #     new_print(self.fifa_account, 'auction_info = ', auction_info)
                            #     new_print(self.fifa_account, 'check_trade = ',
                            #               (self.check_trade(self.main_dic['se_2'], self.main_dic['header_2'],
                            #                                 trade_id)).text)
                    # except:
                    #     print traceback.format_exc()
                    #     time.sleep(30)

                    # break
                    if bad_targets_asset_id and not t_bought:
                        try_to_find_targets += 1
                        self.send_message(
                            bot, 123, f'want buy item but all found item is bad items : {bad_targets_asset_id} ,'
                                      f' {self.fifa_account}. try again'
                        )
                    time.sleep(15)
                    if try_to_find_targets >= 3:
                        self.sender.refresh_from_db()
                        self.sender.has_error = 1
                        self.sender.error_description = 'low gold'
                        self.sender.save(update_fields=['has_error', 'error_description'])
                        self.receiver.refresh_from_db()
                        self.receiver.has_error = 1
                        self.receiver.error_description = 'low gold'
                        self.receiver.save(update_fields=['has_error', 'error_description'])
                        new_print(self.fifa_account, 'after 3 time find target. change it')
                        self.send_message(bot, 123, f'after 3 time not find change receiver.')
                        return 'change receiver'
        except:
            add_time = self.main_dic['fail_number'] * 420
            self.main_dic['fail_number'] += 1
            new_print(self.fifa_account, 'transfer log : ', traceback.format_exc())
            text = f'check transfer log {self.fifa_account}'
            self.send_message(bot, 123, text)
            time.sleep(60 + add_time)
            return 'change receiver'

    def handle_end_bot(self, without_update_time=0):
        new_print(self.fifa_account, 'inside handle end bot , sniper bot')
        # self.sender.fifa_account.refresh_from_db()
        self.sender.fifa_account.active = False
        self.sender.fifa_account.save(update_fields=['active'])
        self.fifa_account.refresh_from_db()
        self.fifa_account.active = False
        self.fifa_account.login_status = 0
        self.fifa_account.driver = False
        self.fifa_account.can_kill_by_mother = False
        self.fifa_account.save()
        # self.receiver.refresh_from_db()
        if not without_update_time:
            self.receiver.last_run_time = timezone.localtime()
        if self.catcher:
            self.catcher.fifa_account.refresh_from_db()
            self.catcher.fifa_account.active = False
            self.catcher.fifa_account.save()
        # self.receiver.has_error = 1
        # self.receiver.error_description = 'manual stop. handle end bot'
        self.receiver.save(update_fields=['last_run_time'])

        new_print(self.fifa_account, 'before revoking task ...')
        if os.name != 'nt':
            try:
                app.control.revoke(self.receiver.task_id, terminate=True, signal='SIGKILL')
            except:
                new_print(self.fifa_account, 'no app found to kill will revoking ...')
        new_print(self.fifa_account, 'after handle end bot , sniper bot')
        raise Exception('After Handle End Bot')

    def sniper_logout_login(self, account_type, worker: SniperAccount, fifa_account: FifaAccount, use_new_sid=True,
                            close_driver=True):
        new_print(self.fifa_account, 'i am in sniper logout login : ', fifa_account)
        if account_type == 'sender':
            worker_key = '1'
        elif account_type == 'catcher':
            worker_key = '3'
        else:
            worker_key = '2'
        # set_sub_log(sbc_worker, 'logout login staff')
        try:
            self.main_dic[f'se_{worker_key}'].close()
            if os.name == 'nt':
                os.system("TASKKILL /F /IM chromedriver.exe")
        except:
            pass
        fifa_backup = fifa_account.account_backup_code.first()
        backup_code = fifa_backup.backup_code
        app_auth = fifa_backup.app_code
        proxy_ip, proxy_port, proxy_user, proxy_pass, proxy_id, self.main_dic[f'se_{worker_key}'] = self.set_proxy(
            fifa_account.id, self.main_dic[f'se_{worker_key}'])
        new_print(self.fifa_account, 'try to login to : ', fifa_account)
        if fifa_account.access_token and fifa_account.nucleus_id and use_new_sid:
            try:
                if self.get_new_sid_by_access_token(worker_key, fifa_account, sid=fifa_account.sid):
                    new_print(self.fifa_account, 'old sid is alive')
                    return True
                else:
                    if fifa_account.use_request_login:
                        try:
                            login_result = LoginWithRequest(
                                fifa_account=fifa_account).new_login(
                                email=fifa_account.user_name, password=fifa_account.password, totp=app_auth,
                                proxy_ip=proxy_ip,
                                proxy_port=proxy_port, proxy_user=proxy_user, proxy_pass=proxy_pass,
                                platform=fifa_account.platform)
                            n_session = login_result.get('session')
                            n_sid = login_result.get('sid')
                            n_persona_id = login_result.get('persona_id')
                            n_nucleus_id = login_result.get('nucleus_id')
                            n_access_token = login_result.get('access_token')
                            personas_list = login_result.get('personas_list', [])
                            time.sleep(2)
                            fifa_account.refresh_from_db()
                            fifa_account.access_token = n_access_token
                            fifa_account.nucleus_id = n_nucleus_id
                            fifa_account.persona_id = n_persona_id
                            fifa_account.sid = n_sid
                            fifa_account.save()
                            self.main_dic[f'se_{worker_key}'] = n_session
                            self.main_dic[f'header_{worker_key}'] = n_session.headers
                            new_print(fifa_account, 'login with request success ')
                            if self.get_new_sid_by_access_token(worker_key, fifa_account,
                                                                sid=fifa_account.sid):
                                new_print(fifa_account, 'sid generated with request work')
                                return True
                        except:
                            new_print(fifa_account, 'login with request failed', traceback.format_exc())
                            fifa_account.requests_cookies = None
                            fifa_account.save(update_fields=['requests_cookies'])
                    new_print(self.fifa_account, 'old sid is done , generate new.')
                if self.get_new_sid_by_access_token(worker_key, fifa_account):
                    time.sleep(0.5)
                    if self.running_platform == 'console':
                        self.update_credit(
                            fifa_account.id, self.main_dic[f'se_{worker_key}'], self.main_dic[f'header_{worker_key}'])
                    else:
                        self.check_account_web_app(fifa_account,
                                                   self.main_dic[f'se_{worker_key}'],
                                                   self.main_dic[f'header_{worker_key}'])
                    time.sleep(0.5)
                    return True
            except:
                new_print(self.fifa_account, 'error in : ', fifa_account, '  ---  ', traceback.format_exc())

        if app_auth:
            backup_code = ''

        fifa_account.refresh_from_db()
        fifa_account.driver = 1
        fifa_account.save()
        fifa_account.refresh_from_db()

        cookies = fifa_account.selenium_cookies
        if cookies:
            try:
                cookies = json.loads(cookies)
            except:
                cookies = None
        try:
            new_print(self.fifa_account, fifa_account, '  proxy data = ', proxy_ip, proxy_port, proxy_user, proxy_pass,
                      proxy_id)
            # TODO :  fix this
            # if os.name == 'nt':
            #     proxy_ip = proxy_port = proxy_user = proxy_pass = ''
            new_print(self.fifa_account, 'proxy_data = ', proxy_ip, proxy_port, proxy_user, proxy_pass)
            self.main_dic[
                f'driver_{worker_key}'], futbin_cookies, need_to_close_ultimate_in_console, need_to_create_club = login_to_account(
                fifa_account.user_name, fifa_account.password, backup_code, use_proxy=1,
                proxy_ip=proxy_ip, proxy_port=proxy_port, proxy_user=proxy_user, proxy_pass=proxy_pass,
                app_auth=app_auth, cookies=cookies)
            if need_to_close_ultimate_in_console and self.running_platform == 'console':
                new_print(self.fifa_account, 'need to close ultimate in console')
                self.main_dic[f'driver_{worker_key}'].close()
                if os.name == 'nt':
                    os.system("TASKKILL /F /IM chromedriver.exe")
            new_print(self.fifa_account, 'need_to_close_ultimate_in_console = ', need_to_close_ultimate_in_console,
                      'need_to_create_club = ', need_to_create_club)
            if need_to_create_club and self.running_platform == 'console':
                new_print(self.fifa_account, 'need ro create club from logout login')
                self.main_dic[f'driver_{worker_key}'].close()
                if os.name == 'nt':
                    os.system("TASKKILL /F /IM chromedriver.exe")

            new_print(self.fifa_account, 'after login', timezone.localtime())


        except:
            new_print(self.fifa_account, 'problem in login : ', fifa_account, ' error : ', traceback.format_exc())
            worker.refresh_from_db()
            worker.has_error = 1
            worker.error_description = 'problem in login'
            worker.save()
            self.handle_end_bot()
            return
        checker = 1
        try:
            if self.main_dic[f'driver_{worker_key}'] == 'proxy dead':
                text = 'proxy %s is dead for ea' % proxy_ip
                new_print(self.fifa_account, 'text = ', text)
                try:
                    FifaProxy.objects.get(id=proxy_id).delete()
                except:
                    pass
                self.send_message(bot, 'critical', text)
                worker.refresh_from_db()
                worker.has_error = 1
                worker.error_description = text
                worker.save()
                self.handle_end_bot(without_update_time=1)
                time.sleep(50)


            if (self.main_dic[f'driver_{worker_key}'] in [
                    'bad_information', '', 'banned', 'app_code_active', 'bad_backup', 'early_access',
                    'need_reset_password']
            ):
                fifa_account.refresh_from_db()
                fifa_account.login_status = 2
                fifa_account.save()
                checker = 0
                text = ''
                if self.main_dic[f'driver_{worker_key}'] == 'banned':
                    text = 'Your account has been disabled %s' % fifa_account.user_name
                    fifa_account.refresh_from_db()
                    fifa_account.delete_club_number = 13
                    fifa_account.save()
                    new_print(self.fifa_account, text)
                    worker.has_error = 1
                    worker.error_description = "account disabled"
                    worker.save(update_fields=['has_error', 'error_description'])
                elif self.main_dic[f'driver_{worker_key}'] == 'bad_backup':
                    text = 'bad backup code %s' % fifa_account.user_name
                    new_print(self.fifa_account, text)
                    if self.running_platform == 'console':
                        worker.status = 'bad_backup'
                        worker.status_change_time = timezone.localtime()
                        worker.description = ''
                        worker.save(update_fields=['status', 'status_change_time', 'description'])
                        time.sleep(100)
                        return 'bad_backup'
                    worker.has_error = 1
                    worker.error_description = "bad backup code"
                    worker.save(update_fields=['has_error', 'error_description'])
                else:
                    new_print(self.fifa_account, 'bad information try 1 more time ... . driver is : ',
                              self.main_dic[f'driver_{worker_key}'])
                    proxy_ip, proxy_port, proxy_user, proxy_pass, proxy_id, self.main_dic[
                        f'se_{worker_key}'] = self.set_proxy(
                        fifa_account.id, self.main_dic[f'se_{worker_key}'], change=1)
                    # TODO : fix this
                    # if os.name == 'nt':
                    #     proxy_ip = proxy_port = proxy_user = proxy_pass = prooxy_id = ''
                    new_print(self.fifa_account, 'proxy_data = ', proxy_ip, proxy_port, proxy_user, proxy_pass)
                    self.main_dic[
                        f'driver_{worker_key}'], futbin_cookies, need_to_close_ultimate_in_console, need_to_create_club = login_to_account(
                        fifa_account.user_name, fifa_account.password, backup_code, use_proxy=1, proxy_ip=proxy_ip,
                        proxy_port=proxy_port,
                        proxy_user=proxy_user, proxy_pass=proxy_pass,
                        app_auth=app_auth, cookies=cookies)
                    if need_to_close_ultimate_in_console and self.running_platform == 'console':
                        self.main_dic[f'driver_{worker_key}'].close()
                        if os.name == 'nt':
                            os.system("TASKKILL /F /IM chromedriver.exe")
                        # self.public_moves.console_open_ultimate()
                        # self.console_close_ultimate()
                        self.main_dic[
                            f'driver_{worker_key}'], futbin_cookies, need_to_close_ultimate_in_console, need_to_create_club = login_to_account(
                            fifa_account.user_name, fifa_account.password, backup_code,
                            use_proxy=1,
                            proxy_ip=proxy_ip,
                            proxy_port=proxy_port,
                            proxy_user=proxy_user, proxy_pass=proxy_pass,
                            app_auth=app_auth, cookies=cookies)
                    if need_to_create_club and self.running_platform == 'console':
                        new_print(self.fifa_account, 'need ro create club from logout login 2')
                        self.main_dic[f'driver_{worker_key}'].close()
                        if os.name == 'nt':
                            os.system("TASKKILL /F /IM chromedriver.exe")
                        # self.public_moves.console_open_ultimate(state_set='play_main')
                        # if self.public_moves.create_club():
                        #     new_print(fifa_account, 'create club successful')
                        #     self.console_close_ultimate()
                        #     self.public_moves.put_on_rest_mode()
                        #     self.sbc_worker.refresh_from_db()
                        #     self.sbc_worker.has_error = True
                        #     self.sbc_worker.error_description = 'create club needed'
                        #     self.sbc_worker.save()
                        #     self.handle_end_bot()
                        #     os.system("TASKKILL /F /IM run_console_manager.exe")
                        #     os.system("TASKKILL /F /IM run_console_manager.exe")
                        #     os.system("TASKKILL /F /IM run_console_manager.exe")
                        #     os.system("TASKKILL /F /IM python.exe")
                        # self.console_close_ultimate()
                        self.main_dic[
                            f'driver_{worker_key}'], futbin_cookies, need_to_close_ultimate_in_console, need_to_create_club = login_to_account(
                            fifa_account.user_name, fifa_account.password, backup_code,
                            use_proxy=1,
                            proxy_ip=proxy_ip,
                            proxy_port=proxy_port,
                            proxy_user=proxy_user, proxy_pass=proxy_pass,
                            app_auth=app_auth, cookies=cookies)

                    if (self.main_dic[f'driver_{worker_key}'] in [
                            'bad_information', '', 'banned', 'app_code_active', 'bad_backup', 'early_access',
                            'need_reset_password']
                        ):
                        new_print(self.fifa_account, 'bad information , driver : ',
                                  self.main_dic[f'driver_{worker_key}'])
                        text = 'cant login to account %s' % fifa_account.user_name
                        worker.refresh_from_db()
                        worker.error_description = "cant login"
                        worker.status = 'login failed'
                        worker.status_change_time = timezone.localtime()
                        worker.save()
                        worker.refresh_from_db()
                        if self.running_platform != 'console':
                            worker.has_error = 1
                            worker.save()
                        else:
                            new_print(self.fifa_account, 'waiting for fixing login data and running again ...')
                            time.sleep(100)
                            self.handle_end_bot()
                            return

                    else:
                        checker = 1
                        new_print(self.fifa_account, 'login successful', timezone.localtime())
                        fifa_account.refresh_from_db()
                        fifa_account.selenium_cookies = json.dumps(self.main_dic[f'driver_{worker_key}'].get_cookies())
                        fifa_account.save(update_fields=['selenium_cookies'])
                if text:
                    new_print(self.fifa_account, 'text = ', text)
                    self.send_message(bot, 'critical', text)
                    worker.refresh_from_db()
                    worker.has_error = 1
                    worker.error_description = text
                    worker.save()
                    self.handle_end_bot()
                    return text
            else:
                checker = 1
                new_print(self.fifa_account, 'login successful', timezone.localtime())
                fifa_account.selenium_cookies = json.dumps(self.main_dic[f'driver_{worker_key}'].get_cookies())
                fifa_account.save(update_fields=['selenium_cookies'])
        except:
            new_print(self.fifa_account, 'web_driver = ', self.main_dic[f'driver_{worker_key}'],
                      ' login failed : ', traceback.format_exc())
            checker = 0
        if checker:
            try:
                fifa_account.refresh_from_db()
                fifa_account.login_status = 1
                fifa_account.save()
                elem = wait_for_element('class', 'one', 'view-navbar-currency-coins',
                                        driver=self.main_dic[f'driver_{worker_key}'], special='break')
                new_print(self.fifa_account, 'check for captcha')
                if not elem:
                    captcha = self.check_captcha(worker_key)
                    if captcha:
                        self.get_new_sid(self.main_dic[f'se_{worker_key}'], worker, account_type)

                    else:
                        # elem = wait_for_element('xpath', 'one', "//button[contains(text(),'Continue')]",
                        #                         special='fast_break',
                        #                         driver=self.main_dic[f'driver_{worker_key}'])
                        # if elem:
                        #     while True:
                        #         elem = wait_for_element('xpath', 'one', "//button[contains(text(),'Continue')]",
                        #                                 special='break', driver=self.main_dic[f'driver_{worker_key}'])
                        #         if elem:
                        #             self.custome_click(elem)
                        #         else:
                        #             break
                        pass
                new_print(self.fifa_account, 'check for captcha completed ...')
                self.main_dic[f'sid_{worker_key}'] = self.main_dic[f'driver_{worker_key}'].execute_script(
                    "return services.Authentication.utasSession.id")
                fifa_account.refresh_from_db()
                fifa_account.sid = self.main_dic[f'sid_{worker_key}']
                fifa_account.save()
                nucleus_id = self.main_dic[f'driver_{worker_key}'].execute_script(
                    "return services.User.getUser().id")
                # persona = driver.execute_script("return services.User.getUser().personas._collection")
                pre_skus = 'FFA23'
                new_sku = 'FFA24'
                platforms_skus = {'ps': [f'{pre_skus}PS4', f'{pre_skus}PS5'], 'xbox360': [f'{pre_skus}XBO'], 'xboxs': [f'{pre_skus}XSX']}
                persona = self.main_dic[f'driver_{worker_key}'].execute_script(
                    "return services.User.getUser().personas[0]['id']")
                new_print(self.fifa_account, 'check for skus')
                try:
                    for i in range(100):
                        skus = self.main_dic[f'driver_{worker_key}'].execute_script(
                            "return services.User.getUser().personas[%s]['_sku']" % i)
                        new_print(self.fifa_account, 'skus = ', skus)
                        if skus in platforms_skus.get(fifa_account.platform, []):
                            persona = self.main_dic[f'driver_{worker_key}'].execute_script(
                                "return services.User.getUser().personas[%s]['id']" % i)
                            new_print(self.fifa_account, 'skus match. persona = ', persona)
                            break
                except:
                    new_print(self.fifa_account, 'no skus for fifa 23')
                try:
                    for i in range(100):
                        skus = self.main_dic[f'driver_{worker_key}'].execute_script(
                            "return services.User.getUser().personas[%s]['_sku']" % i)
                        new_print(self.fifa_account, 'skus = ', skus)
                        if skus == f"{new_sku}PS4" or skus == f'{new_sku}PS5' or skus == f'{new_sku}XBO' or skus == f'{new_sku}XSX':
                            persona = self.main_dic[f'driver_{worker_key}'].execute_script(
                                "return services.User.getUser().personas[%s]['id']" % i)
                            new_print(self.fifa_account, 'skus match. persona = ', persona)
                            break
                except:
                    new_print(self.fifa_account, 'no skus for fifa 22')

                persona = str(persona)
                access_token = self.main_dic[f'driver_{worker_key}'].execute_script(
                    "return window.localStorage.getItem('_eadp.identity.access_token')")
                new_print(self.fifa_account, 'access_token = ', access_token)
                fifa_account.refresh_from_db()
                fifa_account.access_token = access_token
                fifa_account.nucleus_id = nucleus_id
                fifa_account.persona_id = persona
                fifa_account.save()
                # print persona
                # tag = "'id': "
                # persona_id_begin = persona.find(tag) + len(tag)
                # persona_id_end = persona.find(',', persona_id_begin)
                # persona_id = persona[persona_id_begin:persona_id_end]
                new_print(self.fifa_account, 'persona_id = ', persona)
                new_print(self.fifa_account, 'nucleus_id = ', nucleus_id)
                self.main_dic[f'nucleus_id_{worker_key}'] = nucleus_id
                self.main_dic[f'persona_id_{worker_key}'] = persona

                new_print(self.fifa_account, 'sid = ', self.main_dic[f'sid_{worker_key}'])
                # log_file.write('sid = %s'% str(sid))
                # log_file.write('\n')
                # log_file.closed

                # time.sleep(30)

                self.main_dic[f'header_{worker_key}'] = {
                    'Content-Type': 'application/json',
                    'Origin': 'https://www.ea.com',
                    'Referer': 'https://www.ea.com/',
                    'User-Agent': user_agent,
                    'X-UT-SID': self.main_dic[f'sid_{worker_key}'],
                    'Accept': '*/*',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'en-US,en;q=0.5',
                    'Connection': 'keep-alive',
                    'Host': fifa_host,
                }

                if self.running_platform != 'console':
                    error = self.check_account_problems(
                        worker, self.main_dic[f'driver_{worker_key}'],
                        fifa_account.nucleus_id)
                    if error:
                        worker.refresh_from_db()
                        worker.has_error = 1
                        worker.error_description = error
                        worker.save(update_fields=['has_error', 'error_description'])
                        self.handle_end_bot()
                        return error
                if close_driver:
                    self.main_dic[f'driver_{worker_key}'].close()
                    if os.name == 'nt':
                        os.system("TASKKILL /F /IM chromedriver.exe")
                fifa_account.refresh_from_db()
                fifa_account.driver = 0
                fifa_account.save()
                if self.running_platform == 'inject':
                    MuleAccounts.objects.filter(fifa_account=fifa_account).update(
                        last_sid=self.main_dic[f'sid_{worker_key}'],
                        last_nucleus=self.main_dic[f'nucleus_id_{worker_key}'],
                        last_persona=self.main_dic[f'persona_id_{worker_key}'])
            except:
                new_print(self.fifa_account, 'error 81 : ', traceback.format_exc())

    def get_new_sid_by_access_token(self, worker_key, fifa_account, sid=None, game_sku=None):
        if not game_sku:
            pre_game_sku = 'FFA25'  # TODO: maybe read from shards v2
            if fifa_account.platform == 'pc':  # TODO: get this from shards
                game_sku = '%sPCC' % pre_game_sku
            elif fifa_account.platform == 'xbox360':
                game_sku = '%sXBO' % pre_game_sku
            elif fifa_account.platform == 'xboxs':
                game_sku = '%sXSX' % pre_game_sku
            elif fifa_account.platform in ['ps', 'ps4']:
                game_sku = '%sPS4' % pre_game_sku
            elif fifa_account.platform == 'ps5':
                game_sku = '%sPS5' % pre_game_sku
            else:
                raise Exception('Wrong platform. (Valid ones are pc/xbox/xbox360/ps3/ps4/ps5)')
        if not sid:
            # url = "https://accounts.ea.com/connect/auth?client_id=FC24_JS_WEB_APP&redirect_uri=nucleus:rest&response_type=code&access_token=" \
            #       "%s" \
            #       "&release_type=prod&client_sequence=ut-auth" % fifa_account.access_token
            url = accounts_ea_auth_url

            auth_params = {
                'client_id': 'FUTWEB_BK_OL_SERVER',
                'redirect_uri': 'nucleus:rest',
                'response_type': 'code',
                'access_token': str(self.fifa_account.access_token),
                'release_type': 'prod',
                'client_sequence': 'ut-auth',
            }
            headers = {
                'Content-Type': 'application/json',
                'Host': fifa_host,
                'Origin': 'https://www.ea.com',
                'Referer': 'https://www.ea.com/',
                'User-Agent': user_agent,
                'Accept': 'text/plain, */*; q=0.01'
            }

            # response = requests.request("GET", url, headers=headers, data=payload)
            response = self.main_dic[f'se_{worker_key}'].get(url, headers=headers, params=auth_params)
            # todo : fix data. json response has error
            new_print(self.fifa_account, 'ea auth response : ', response.text)
            json_resp = response.json()
            if json_resp.get('error', ''):
                new_print(self.fifa_account, 'access token is expired. need a new one')
                return False
            auth_code = json_resp['code']
            new_print(self.fifa_account, 'auth_code = ', auth_code)
            url2 = f"https://{fifa_host}/ut/auth"
            payload = {
                "isReadOnly": False,
                "sku": fut_web_number,
                "clientVersion": 1,
                "locale": "en-US",
                "method": "authcode",
                "priorityLevel": 4,
                "identification": {
                    "authCode": auth_code,
                    "redirectUrl": "nucleus:rest"
                },
                "nucleusPersonaId": int(fifa_account.persona_id),
                "gameSku": game_sku,
                "ds": "66ddb7e2d74792bacf29dbc351e380e66f55d567b6572420163fefb603c2888f/2f2c"
            }
            new_print(self.fifa_account, 'payload = ', payload)
            headers = {
                'Content-Type': 'application/json',
                'Origin': 'https://www.ea.com',
                'Referer': 'https://www.ea.com/',
                'Host': fifa_host,
                'User-Agent': user_agent,
                'Accept': 'text/plain, */*; q=0.01'
            }

            # response = requests.request("POST", url, headers=headers, data=payload)
            response = self.main_dic[f'se_{worker_key}'].post(url2, json=payload, headers=headers, )

            new_print(self.fifa_account, 'auth response : ', response.status_code, response.text)
            try:
                json_resp = response.json()
                if json_resp.get('sid', ''):
                    new_print(self.fifa_account, 'getting new sid is ok . new sid = ', json_resp['sid'])
                    self.main_dic[f'sid_{worker_key}'] = json_resp['sid']
                    self.main_dic[f'header_{worker_key}'] = self.main_dic[f'se_{worker_key}'].headers
                else:
                    new_print(self.fifa_account, 'app auth not working. will use the normal get new sid')
                    return False
            except:
                new_print(self.fifa_account, 'app auth not working. will use the normal get new sid : ',
                          traceback.format_exc())
                return False
        else:
            try:
                self.main_dic[f'nucleus_id_{worker_key}'] = fifa_account.nucleus_id
                self.main_dic[f'persona_id_{worker_key}'] = fifa_account.persona_id

                # global pin_enevts_data
                self.main_dic[f'header_{worker_key}'] = {
                    'Content-Type': 'application/json',
                    'Origin': 'https://www.ea.com',
                    'Referer': 'https://www.ea.com/',
                    'User-Agent': user_agent,
                    'X-UT-SID': sid,
                    'Accept': '*/*',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'en-US,en;q=0.5',
                    'Connection': 'keep-alive',
                    'Host': fifa_host,
                }
                self.main_dic[f'se_{worker_key}'].headers.update(self.main_dic[f'header_{worker_key}'])
                check_resp = self.main_dic[f'se_{worker_key}'].get(
                    f'{fifa_23_address}/user/credits'
                )
                new_print(self.fifa_account, 'get new sid get credit result : ', check_resp, check_resp.text[:100])
                json_check_resp = check_resp.json()
                if json_check_resp.get('credits', None) is not None:
                    self.main_dic[f'sid_{worker_key}'] = sid
                if json_check_resp.get('reason', '') == 'expired session':
                    return False
            except:
                new_print(self.fifa_account, 'old sid has error : ', traceback.format_exc())
                return False

        self.main_dic[f'nucleus_id_{worker_key}'] = fifa_account.nucleus_id
        self.main_dic[f'persona_id_{worker_key}'] = fifa_account.persona_id

        fifa_account.refresh_from_db()
        fifa_account.sid = self.main_dic[f'sid_{worker_key}']
        fifa_account.save(update_fields=['sid'])

        # global pin_enevts_data
        self.main_dic[f'header_{worker_key}'] = {
            'Content-Type': 'application/json',
            'Origin': 'https://www.ea.com',
            'Referer': 'https://www.ea.com/',
            'User-Agent': user_agent,
            'X-UT-SID': self.main_dic[f'sid_{worker_key}'],
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'en-US,en;q=0.5',
            'Connection': 'keep-alive',
            'Host': fifa_host,
        }
        return True

    def check_account_web_app(self, fifa_account, se, header):
        time.sleep(2)
        resp = se.get(f'{fifa_23_address}/watchlist',
                      headers=header)
        new_print(self.fifa_account, 'check account_healthy resp = ', resp.text)
        json_resp = resp.json()
        credit = json_resp['credits']
        # fifa_account.refresh_from_db()
        fifa_account.credit = credit
        fifa_account.save(update_fields=['credit'])
        fifa_account.refresh_from_db()
        # time.sleep(20)

    # def set_this_staff_to_pass_logout_login(self):
    #     # proxy = self.fifa_account.proxy
    #     # if proxy:
    #     #     self.proxy_ip = proxy.ip_address
    #     #     self.proxy_port = proxy.port
    #     #     self.proxy_user = proxy.user_name
    #     #     self.proxy_pass = proxy.password
    #     # self.main_dic['futbin_cookies'] = ''
    #     self.main_dic['pin_enevts_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',
    #                                           'Host': fifa_host,
    #                                           'x-ea-game-id': fut_web_number, 'x-ea-game-id-type': 'easku',
    #                                           'x-ea-taxv': '1.1',
    #                                           }
    #     self.main_dic['pin_enevts_option_header'] = {
    #         'Access-Control-Request-Headers': 'content-type,x-ea-game-id,x-ea-game-id-type,x-ea-taxv',
    #         'Access-Control-Request-Method': 'POST',
    #         'Origin': 'https://www.ea.com',
    #         'Referer': 'https://www.ea.com/',
    #         'User-Agent': user_agent,
    #     }
    #     self.main_dic['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': 'GET',
    #                                        'Origin': 'https://www.ea.com',
    #                                        'Referer': 'https://www.ea.com/',
    #                                        'User-Agent': user_agent
    #                                        }

    def check_captcha(self, worker_key):
        elem = wait_for_element('xpath', 'one', "//h2[contains(text(),'Verification Required')]", special='break',
                                driver=self.main_dic[f'driver_{worker_key}'])
        if elem:
            new_print(self.fifa_account, 'captcha found')
            return 1
        return 0
