import ast
import json
import os
import random
import shutil
import time
import traceback
from random import randint

import cloudscraper
import requests
import telepot
import unidecode
from bs4 import BeautifulSoup
from django.db import close_old_connections
from django.db.models import Count
from django.utils import timezone
from django.utils.timezone import get_current_timezone
from selenium.webdriver import ActionChains

from accounts.models import FifaAccount, FifaProxy, PlayerCard, FifaAccountSearch, MuleAccounts, ConsoleBotSetting
from futplus.celery_conf import app
from futplus.settings import BASE_DIR
from sbc import FIFA_REPORT_TOKEN
from sbc.login_to_ea_with_selenium import login_to_account, wait_for_element
from sbc.public_methods import new_print, get_round_price, get_previous_price_grade, force_get, get_next_price_grade, \
    get_trade_pile_2, most_common, put_item_for_sale, get_round_top_price, delete_sold_items, \
    get_player_data_by_asset_id, clear_outbid, get_watchlist
from trade.models import TradeLog, TradeWorker, SinglePlayerTradeWorker
from utils.ea_settings import fifa_host, fifa_23_address
from utils.tools import select_platform

file_path = os.path.dirname(os.path.abspath(__file__))
bot = telepot.Bot(FIFA_REPORT_TOKEN)

user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'

class TraderBot:
    def __init__(self, fifa_account: FifaAccount, trade_worker):
        self.se = requests.Session()
        self.se_header = {}
        self.se2 = requests.session()
        self.fifa_account = fifa_account
        self.running_platform = trade_worker.running_platform
        self.web_driver = None
        self.proxy_ip = None
        self.proxy_port = None
        self.proxy_user = None
        self.proxy_pass = None
        self.trade_worker = trade_worker
        # self.platform_key = select_platform[fifa_account.platform]['platform_key']
        self.platform_key = select_platform['ps']['platform_key']

        fifa_backup = self.fifa_account.account_backup_code.first()
        self.backup_code = fifa_backup.backup_code
        self.app_auth = fifa_backup.app_code

        self.persona_id = self.fifa_account.persona_id
        self.nucleus_id = self.fifa_account.nucleus_id

        self.job_time_id = 0
        self.first_buy = 0
        self.first_sold = 0
        self.check_bug = 0
        self.start_time = timezone.localtime()
        self.temp_bid = 0
        self.temp_buy = 0
        self.first_check = 0
        self.soft_ban_counter = 0
        self.bid_controller_count = 0
        self.bid_controller_time = timezone.localtime()
        self.bid_controller_report = 0
        self.win_controller_count = 0
        self.target_controller_count = 0
        self.weak_target_controller_count = 0
        self.captcha_start_time = ''
        self.captcha_end_time = ''
        self.loop_controller_count = 0
        self.temperory_not_bid = 0
        self.bug_count = 0
        self.fixed_bug_count = 0
        self.search_min_time = 0
        self.search_max_time = 0
        self.transfer_list_len = 0
        self.transfer_more_than_limit = 0
        self.number_of_searchs = 0
        self.temp_number_of_searchs = 0
        self.reporter_time = timezone.localtime()
        self.temp_bid_controller = 0
        self.temp_win_controller = 0
        self.remaining_buys = 0
        self.invest_id = 0
        self.invest_sell_check = 0
        self.sleep_time = 0
        self.check_proxy = 0
        self.first_xi = 0
        self.puzzle_master = 0
        self.no_xi = 0
        self.no_master = 0
        self.empty_bid_handler = 0
        self.first_buy_items = 0
        self.no_credit = 0
        self.no_good_pack = 0
        self.begin_new_sid = timezone.localtime()
        self.end_new_sid = timezone.localtime() + timezone.timedelta(seconds=3)
        self.third_sbc_problem = 0
        self.last_sbc_failed = 0
        self.proxy_ip = ''
        self.proxy_port = ''
        self.new_sid_set = 0
        self.soft_ban_handler = 0
        self.completed = 0
        self.account_high_search_count = ConsoleBotSetting.objects.get(name='account_high_search_count').int_value

    def update_session_proxy(self, account_id, se, proxy_id, proxy_ip, proxy_port, proxy_user, proxy_pass):
        proxies = {'https': 'http://%s:%s@%s:%s' % (proxy_user, proxy_pass, proxy_ip, proxy_port)}
        se.proxies.update(proxies)
        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)
            # handle_end_bot()
            # time.sleep(30)
            new_print(self.fifa_account, text)
            return 'failed'
        fifa_account = FifaAccount.objects.get(id=account_id)
        fifa_account.proxy = FifaProxy.objects.get(id=proxy_id)
        fifa_account.save(update_fields=['proxy'])
        new_print(self.fifa_account, 'proxy_id = ', proxy_id)
        return 'ok'

    def set_proxy(self, account_id, se, change=0):
        fifa_account = FifaAccount.objects.get(id=account_id)
        last_proxy_id = 0
        account_proxy = fifa_account.proxy
        if change:
            last_proxy_id = account_proxy.id
            fifa_account.refresh_from_db()
            fifa_account.proxy = None
            fifa_account.save(update_fields=['proxy'])
            account_proxy = None
        temp_set_proxy = 0
        if not account_proxy:
            new_print(self.fifa_account, 'account has no proxy. try to set new proxy', fifa_account)
            temp_set_proxy = 1
            all_exist = 1
            for proxy in FifaProxy.objects.filter(type_name=''):
                exist = FifaAccount.objects.filter(proxy=proxy)
                if not exist:
                    if change and last_proxy_id == proxy.id:
                        continue
                    all_exist = 0
                    status = self.update_session_proxy(account_id, se, proxy.id, proxy.ip_address, proxy.port,
                                                       proxy.user_name, proxy.password)
                    if status == 'failed':
                        new_print(self.fifa_account, 'proxy set failed .', proxy)
                        return '', '', '', '', 0, se
                    account_proxy = proxy

                    break
            if all_exist or (not account_proxy):
                proxy_list_id = FifaAccount.objects.exclude(proxy=None).filter(
                    proxy__type_name=''
                ).values('proxy').annotate(
                    proxy_count=Count('proxy')).order_by('proxy_count').values_list('proxy__id', flat=True)
                proxy = FifaProxy.objects.get(id=proxy_list_id[0])
                if change and last_proxy_id == proxy.id:
                    proxy = FifaProxy.objects.get(id=proxy_list_id[1])
                new_print(self.fifa_account, 'proxy_id = ', proxy.id)
                status = self.update_session_proxy(account_id, se, proxy.id, proxy.ip_address, proxy.port,
                                                   proxy.user_name, proxy.password)
                if status == 'failed':
                    new_print(self.fifa_account, 'proxy set failed 2 . ', proxy)
                    return '', '', '', '', 0, se
                account_proxy = proxy

        PROXY_HOST = account_proxy.ip_address
        PROXY_PORT = account_proxy.port
        PROXY_USER = account_proxy.user_name
        PROXY_PASS = account_proxy.password
        if not temp_set_proxy:
            try:
                proxies = {'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, 'proxy set resp = ', resp.text)
            except:
                new_print(self.fifa_account, traceback.format_exc())
                text = 'proxy is expired for account %s' % fifa_account.user_name
                # send_message(bot,123,text)
                # handle_end_bot()
                # time.sleep(50)
                new_print(self.fifa_account, text)
                return '', '', '', '', 0, se

        return PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASS, account_proxy.id, se

    def update_credit(self, ):
        time.sleep(2)
        resp = self.se.get(f'{fifa_23_address}/tradepile',
                           headers=self.se_header)
        new_print(self.fifa_account, 'update credit resp = ', resp.text[:100])
        json_resp = resp.json()
        credit = json_resp['credits']
        self.fifa_account.credit = credit
        self.fifa_account.save()
        self.fifa_account.refresh_from_db()

    def get_plus_credit(self):
        resp = self.se.get(f'{fifa_23_address}/watchlist',
                           headers=self.se_header)
        json_resp = resp.json()
        credit = json_resp['credits']
        for trade_item in json_resp['auctionInfo']:
            if trade_item['bidState'] == 'highest':
                credit += int(trade_item['currentBid'])
        resp = get_trade_pile_2(self.fifa_account, self.se, self.options_header, self.se_header)
        json_resp = resp.json()
        trades = json_resp['auctionInfo']
        sum_buy_now = 0
        for trade in trades:
            if trade['tradeState'] == 'active':
                sum_buy_now += trade['buyNowPrice']
            if trade.get('tradeState', None) is None:
                credit += trade.get('itemData', {}).get('lastSalePrice', 0)
        sum_buy_now = sum_buy_now - ((sum_buy_now * 5) / 100)
        credit = credit + sum_buy_now
        return credit

    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.futbin_cookies = ''
        self.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': 'FUT24WEB', 'x-ea-game-id-type': 'easku',
                                  'x-ea-taxv': '1.1'
                                  }
        self.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.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 get_new_sid_by_access_token(self, sid=None):
        if not sid:
            if not self.se_header:
                self.set_this_staff_to_pass_logout_login()

            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" % self.fifa_account.access_token

            payload = {}
            headers = {
                'Content-Type': 'application/json',
                'Host': 'accounts.ea.com',
                '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.se.get(url, headers=headers, data=payload)
            # 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 = "https://utas.mob.v1.fut.ea.com/ut/auth"

            payload = {
                "isReadOnly": False,
                "sku": "FUT24WEB",
                "clientVersion": 1,
                "locale": "en-US",
                "method": "authcode",
                "priorityLevel": 4,
                "identification": {
                    "authCode": auth_code,
                    "redirectUrl": "nucleus:rest"
                },
                "nucleusPersonaId": int(self.fifa_account.persona_id),
                "gameSku": "FFA23PS4",
                "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.se.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.sid = json_resp['sid']
                    self.se_header.update(self.se.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:
            if not self.se_header:
                self.set_this_staff_to_pass_logout_login()
            try:
                self.nucleus_id = self.fifa_account.nucleus_id
                self.persona_id = self.fifa_account.persona_id

                # global pin_enevts_data
                self.se_header = {
                    '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,
                }
                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
                check_resp = self.check_trade(fake_trade_id)
                json_check_resp = check_resp.json()
                if json_check_resp.get('auctionInfo'):
                    self.sid = 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.nucleus_id = self.fifa_account.nucleus_id
        self.persona_id = self.fifa_account.persona_id

        self.fifa_account.refresh_from_db()
        self.fifa_account.sid = self.sid
        self.fifa_account.save()

        # global pin_enevts_data
        self.se_header = {
            'Content-Type': 'application/json',
            'Origin': 'https://www.ea.com',
            'Referer': 'https://www.ea.com/',
            'User-Agent': user_agent,
            'X-UT-SID': self.sid,
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'en-US,en;q=0.5',
            'Connection': 'keep-alive',
            'Host': fifa_host,
        }
        return True

    def get_new_sid(self, ):
        try:
            text = 'start getting new sid'
            new_print(self.fifa_account, text)
            if self.trade_worker.has_error:
                time.sleep(2)
                new_print(self.fifa_account, 'bot is done')
                raise Exception('must done bot')
            self.fifa_account.refresh_from_db()
            if not self.fifa_account.active:
                self.fifa_account.active = True
                self.fifa_account.save()

            if not self.fifa_account.need_captcha:
                if self.fifa_account.access_token and self.fifa_account.nucleus_id:
                    try:
                        if self.get_new_sid_by_access_token():
                            time.sleep(0.5)
                            self.update_credit()
                            time.sleep(0.5)
                            return
                    except:
                        new_print(self.fifa_account, traceback.format_exc())

                self.begin_new_sid = timezone.localtime()
                self.fifa_account.driver = 1
                self.fifa_account.save()
                self.fifa_account.refresh_from_db()

                refresh_count = 0
                while True:
                    if refresh_count >= 1:
                        break

                    # new_print(self.fifa_account,'number of refresh count in get new sid = ', refresh_count)
                    text = 'number of refresh count in get new sid = ' + str(refresh_count)
                    new_print(self.fifa_account, text)
                    try:
                        try:
                            self.web_driver.get('https://www.ea.com/fifa/ultimate-team/web-app/')
                        except:
                            cookies = self.fifa_account.cookies
                            if cookies:
                                cookies = ast.literal_eval(cookies)
                            new_print(self.fifa_account, 'proxy_data = ', self.proxy_ip,
                                      self.proxy_port,
                                      self.proxy_user, self.proxy_pass)
                            self.web_driver, self.futbin_cookies, need_to_close_ultimate_in_console, need_to_create_club = login_to_account(
                                self.fifa_account.user_name, self.fifa_account.password,
                                '', use_proxy=1, proxy_ip=self.proxy_ip,
                                proxy_port=self.proxy_port, proxy_user=self.proxy_user,
                                proxy_pass=self.proxy_pass, app_auth=self.app_auth, cookies=cookies
                            )
                    except:
                        new_print(self.fifa_account, traceback.format_exc())

                        # self.handle_end_bot()
                        # self.send_message(bot, '123', 'check account sbc log %s' % self.fifa_account.user_name)
                        # raise Exception('must done bot')
                        # logout_login(self, self.trade_worker, self.fifa_account, use_new_sid=False)

                    elem = wait_for_element('class', 'one', 'view-navbar-currency-coins', special='captcha',
                                            driver=self.web_driver)
                    self.web_driver.get_screenshot_as_file(file_path + '/logs/sid%s.png' % str(self.fifa_account.id))
                    signed_in_elem = wait_for_element('xpath', 'one',
                                                      "//h2[contains(text(),'Signed Into Another Device')]",
                                                      special='break',
                                                      driver=self.web_driver)
                    if signed_in_elem:
                        new_print(self.fifa_account, 'console login w8 5 minutes')
                        time.sleep(300)
                        continue

                    refresh_count += 1
                    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.web_driver)
                        if not elem:
                            try:
                                new_print(self.fifa_account, 'not elem')
                                elem = wait_for_element('class', 'one', 'call-to-action',
                                                        driver=self.web_driver)
                                ActionChains(self.web_driver).move_to_element(elem).click().perform()
                                elem = wait_for_element('class', 'one', 'view-navbar-currency-coins',
                                                        driver=self.web_driver)
                                if elem:
                                    break
                            except:
                                pass
                        else:
                            new_print(self.fifa_account, 'captcha found')
                            self.web_driver.get_screenshot_as_file(
                                file_path + '/logs/captcha%s.png' % str(self.fifa_account.id))

                            self.captcha_start_time = timezone.localtime()
                            self.fifa_account.need_captcha = 1
                            self.fifa_account.save()
                            self.fifa_account.refresh_from_db()

                            self.send_message(bot, -1001208022772,
                                              'captcha need . automatic solve for %s' % (self.fifa_account.user_name))

                            cookies = self.web_driver.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' % self.fifa_account.user_name
                                self.send_message(bot, 123, text)
                                new_print(self.fifa_account, text)
                                time.sleep(300)
                                return
                            payload = "{\"proxy_port\": \"%s\", \"proxy_ip\": \"%s\", \"proxy_user\": \"%s\", \"fingerprint\": \"\", \"device\": \"WEB\", \"userAgent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36\", \"console\": \"PS\", \"proxy_pass\": \"%s\", \"nx_mpcid\": \"%s\", \"proxy_type\": \"HTTP\", \"sessionId\": \"%s\", \"futEmail\": \"%s\", \"api_key\": \"ccbf62d7921a1c4b4f9cdc0fa18ece52\", \"nucleusId\": %s,\"user\": \"simonhains\",\"pass\":\"zmvLAS0193\"}" % (
                                str(self.proxy_port), self.proxy_ip
                                , self.proxy_user, self.proxy_pass, nx_mpcid,
                                self.web_driver.execute_script("return services.Authentication.sessionUtas.id"),
                                self.fifa_account.user_name,
                                self.web_driver.execute_script("return services.User.getUser().id")
                            )
                            headers = {
                                'content-type': "application/json"
                            }
                            new_print(self.fifa_account, 'before request')
                            new_print(self.fifa_account, 'data = ', payload)
                            resp = requests.post('https://api.dmapi.co/fcapi/solve.php', data=payload,
                                                 headers=headers)
                            try:
                                json_resp = resp.json()
                                if json_resp['EA_VALIDATED'] == 1 and json_resp['FC_SOLVED'] == 1:
                                    self.fifa_account.need_captcha = 0
                                    self.fifa_account.save()
                                    self.fifa_account.refresh_from_db()
                                    # cursor2.execute(
                                    #     'update accounts set description = "captcha solved" , captcha = 0 where account_email = %s',
                                    #     (self.fifa_account.user_name,))

                                    self.send_message(bot, -1001208022772,
                                                      'captcha solved for %s' % self.fifa_account.user_name)
                                    time.sleep(5)
                                    self.web_driver.get('https://www.ea.com/fifa/ultimate-team/web-app/')
                                    wait_for_element('class', 'one', 'view-navbar-currency-coins',
                                                     driver=self.web_driver)
                                    refresh_count = 2

                                    # break
                                else:
                                    text = 'cant solve captcha for %s' % self.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, traceback.format_exc())
                                text = 'cant solve captcha for %s' % self.fifa_account.user_name
                                self.send_message(bot, 'critical', text)
                                new_print(self.fifa_account, text)
                                time.sleep(300)
                                return

                self.sid = self.web_driver.execute_script(
                    "return services.Authentication.sessionUtas.id")
                self.fifa_account.refresh_from_db()
                self.fifa_account.sid = self.sid
                self.fifa_account.save()

                self.nucleus_id = self.web_driver.execute_script(
                    "return services.User.getUser().id")

                platforms_skus = {'ps': ['FFA23PS4', 'FFA23PS5'], 'xbox360': ['FFA23XBO'], 'xboxs': ['FFA23XSX']}
                persona = self.web_driver.execute_script("return services.User.getUser().personas[0]['id']")
                for i in range(100):
                    skus = self.web_driver.execute_script(
                        "return services.User.getUser().personas[%s]['_sku']" % i)
                    if skus in platforms_skus.get(self.fifa_account.platform, []):
                        persona = self.web_driver.execute_script(
                            "return services.User.getUser().personas[%s]['id']" % i)
                        break
                persona = str(persona)
                access_token = self.web_driver.execute_script(
                    "return window.localStorage.getItem('_eadp.identity.access_token')")
                new_print(self.fifa_account, 'access_token = ', access_token)
                self.fifa_account.refresh_from_db()
                self.fifa_account.access_token = access_token
                self.fifa_account.nucleus_id = self.nucleus_id
                self.fifa_account.persona_id = persona
                self.fifa_account.save()

                self.persona_id = int(persona)
                new_print(self.fifa_account, 'persona_id = ', self.persona_id)
                new_print(self.fifa_account, 'nucleus_id = ', self.nucleus_id)
                new_print(self.fifa_account, 'sid = ', self.sid)

                # global pin_enevts_data
                self.se_header = {
                    'Content-Type': 'application/json',
                    'Origin': 'https://www.ea.com',
                    'Referer': 'https://www.ea.com/',
                    'User-Agent': user_agent,
                    'X-UT-SID': self.sid,
                    'Accept': '*/*',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'en-US,en;q=0.5',
                    'Connection': 'keep-alive',
                    'Host': fifa_host,
                }
                self.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': 'FUT24WEB', 'x-ea-game-id-type': 'easku',
                                          'x-ea-taxv': '1.1'
                                          }
                self.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.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.web_driver.get_screenshot_as_file('get_new_sid_tmp.png')
                self.end_new_sid = timezone.localtime()
                self.web_driver.close()
                if os.name == 'nt':
                    os.system("TASKKILL /F /IM chromedriver.exe")

                self.fifa_account.refresh_from_db()
                self.fifa_account.driver = 0
                self.fifa_account.save()

                # cursor2.execute('update accounts set driver = 0 where id = %s', (self.account_id,))

            else:
                new_print(self.fifa_account, 'captcha set in database')
        except:
            new_print(self.fifa_account, traceback.format_exc())
            raise Exception('error in get sid')
        # time.sleep(20)

    def check_trade(self, trade_id):
        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.se.options(
            f'{fifa_23_address}/trade/status/lite?tradeIds=%s' % (str(trade_id),),
            headers=options_header)
        resp = force_get(
            f'{fifa_23_address}/trade/status/lite?tradeIds=%s' % (str(trade_id),),
            self.fifa_account,
            self.se,
            self.se_header)
        new_print(self.fifa_account, 'check trade : ', trade_id)
        return resp

    def search_player(self, player_id, max_price, search_type, number='21', start='0', rare=0, pos='', link='', team=0,
                      safe=True):

        FifaAccountSearch.objects.create(fifa_account=self.fifa_account, search_time=timezone.localtime())
        search_number = self.fifa_account.account_search.filter(
            search_time__gt=timezone.localtime() - timezone.timedelta(hours=24)).count()
        new_print(self.fifa_account, 'search_number = ', search_number)

        if (search_number + 1 > self.account_high_search_count) and (
                self.running_platform == 'web' or self.running_platform == 'inject'):
            self.trade_worker.error_description = "high search"
            self.trade_worker.has_error = 1
            self.trade_worker.save()
            text = 'search number more than 300 for account %s' % self.fifa_account.user_name
            resp = get_trade_pile_2(self.fifa_account, self.se, self.options_header, self.se_header)
            json_resp = resp.json()
            trades = json_resp['auctionInfo']
            sum_active_trades = 0
            sum_starting_bids = 0
            for trade_object in trades:
                if trade_object['tradeState'] == 'active' or trade_object['tradeState'] == 'expired':
                    sum_active_trades += 1
                    sum_starting_bids += trade_object['startingBid']
            add_part = '\nnumber of active trades = %s\nactive trades starting bids sum = %s' % (
                sum_active_trades, sum_starting_bids)

            self.send_message(bot, 'critical', text + add_part)
            self.handle_end_bot()
            return 'sid'
            time.sleep(50)
        # print 'in search'
        rare_item = ''
        if rare > 1:
            rare_item = 'SP'

        if self.running_platform != 'inject':
            time.sleep(randint(2, 3))
        # time.sleep(1)
        # while True:
        #     if self.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)
                # bellow condition added for break caching search result
                if sp == 'macr':
                    search_part = search_part + '&' + 'maxb' + '=' + str(get_round_price(
                        int(max_price) + random.randint(100000, 500000)
                    ))
            pos_part = ''
            if pos:
                pos_part = '&pos=' + pos
            team_part = ''
            if team:
                team_part = '&team=' + str(team)
            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
                              }
            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=%d%s%s%s%s%s' % (
                    start, number, player_id, search_part, rare_part, pos_part, rarity, team_part)
            if safe:
                self.se.options(link, headers=options_header)
            # new_print(self.fifa_account,link, self.se_header)
            resp = force_get(link, self.fifa_account, self.se, self.se_header)
            if safe:
                try:
                    json_resp = resp.json()
                    auction_info = json_resp['auctionInfo']
                except:
                    new_print(self.fifa_account, 'search auction error , resp : ', resp.text)
                    time.sleep(2)
                    resp = force_get(link, self.fifa_account, self.se, self.se_header)
                    # print 'new search result = ',resp.content
                # print 'link =', link
                # print "self.se_header = ",self.se_header
                # print 'resp.content = ', resp.content
                # time.sleep(10)

                # self.se.options('https://pin-river.data.ea.com/pinEvents', headers=self.main_dic['pin_enevts_option_header'])
                now_time = timezone.localtime()
                ea_now_time = now_time + timezone.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 + timezone.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": "FUT24WEB", "tidt": "easku",
                                   "ts_post": "%sT%sZ", "v": "23.0.2",
                                   "sid": "%s"}''' % (
                    self.platform_key, str(self.fifa_account.persona_id), ea_now_time_date, ea_now_time_time,
                    str(self.nucleus_id),
                    self.se_header['X-UT-SID'],
                    ea_now_time_plus_date, ea_now_time_plus_time)
                try:
                    self.se.post('https://pin-river.data.ea.com/pinEvents', data=pin_enevts_data,
                                 headers=self.pin_enevts_header, timeout=2)
                except:
                    new_print(self.fifa_account, 'pin events data sent failed')
                self.number_of_searchs += 1
                self.temp_number_of_searchs += 1

            return resp
        except Exception as e:
            new_print(self.fifa_account, traceback.format_exc())

    def bid_trade(self, trade_id, data, safe=True):
        if safe:
            options_header = {'Accept': '*/*',
                              'Accept-Encoding': 'gzip, deflate, br',
                              'Accept-Language': 'en-US,en;q=0.5',
                              'Connection': 'keep-alive',
                              'Host': fifa_host,
                              'Access-Control-Request-Headers': 'content-type,x-ut-sid',
                              'Access-Control-Request-Method': 'PUT',
                              'Origin': 'https://www.ea.com',
                              'Referer': 'https://www.ea.com/',
                              'User-Agent': user_agent
                              }
            self.se.options(
                f'{fifa_23_address}/trade/%s/bid' % (trade_id,),
                headers=options_header)
        resp = self.se.put(
            f'{fifa_23_address}/trade/%s/bid' % (trade_id,),
            data=data, headers=self.se_header)
        return resp

    def use_cloud_scraper(self, link):
        new_print(self.fifa_account, 'link = ', link)
        counter = 0
        while True:
            new_print(self.fifa_account, 'counter = ', counter, 'proxie = ', self.proxy_ip,
                      self.proxy_port)
            counter += 1
            scraper = cloudscraper.create_scraper(browser={
                'browser': 'firefox',
                'platform': 'linux',
                'mobile': False
            })
            if str(self.proxy_ip):
                proxies = {'https': 'http://%s:%s@%s:%s' % (
                    str(self.proxy_user), str(self.proxy_pass), str(self.proxy_ip),
                    str(self.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.fifa_account.user_name, self.proxy_ip))
        return resp.text

    def get_price_from_futbin_and_futwiz(self, player_asset_id):
        resp = self.use_cloud_scraper('https://www.futbin.com/24/playerPrices?player=%s' % player_asset_id)
        try:
            # json_resp = resp.json()
            json_resp = json.loads(resp)
        except:
            new_print(self.fifa_account, resp)
            new_print(self.fifa_account, traceback.format_exc())
            if resp.find('Your client does not have permission') != -1:
                text = 'proxy %s:%s is dead for futbin' % (self.proxy_ip, self.proxy_port)
                self.send_message(bot, 'critical', text)

                proxy = FifaProxy.objects.filter(ip_address=self.proxy_ip,
                                                 port=self.proxy_port).first()
                if proxy:
                    proxy.delete()
                last_run = timezone.localtime() - timezone.timedelta(hours=2)
                self.trade_worker.last_run_time = last_run
                self.trade_worker.save()

                self.handle_end_bot(without_update_time=1)
                return

            time.sleep(3000)

        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 = str(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 = self.se2.get(futwiz_base_url + '/en/player/history/%s' % player_asset_id)
        #     # soup = BeautifulSoup(resp.content, "html.parser")
        #     new_print(self.fifa_account,futwiz_base_url + '/en/player/history/%s' % player_asset_id)
        #     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 = self.se2.get(futwiz_base_url + a_elem_href)
        #     # soup = BeautifulSoup(resp.content, "html.parser")
        #     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(str(price).replace(',', ''))
        first_price = int(str(first_price).replace(',', ''))
        return price, futbin_price_update_time, first_price, futbin_min_price, futbin_max_price

    def compare_futbin_price_with_local_data(self, local_data, price, updated_time):
        if local_data:
            new_print(self.fifa_account, 'local data found')
            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() - timezone.timedelta(minutes=int(updated_time_min[0]))
                    new_print(self.fifa_account, 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() - timezone.timedelta(hours=int(updated_time_hour[0]))
                    new_print(self.fifa_account, 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 account_sbc_targets_buy_staff(self, accounts_sbc_id, bid_resp, position, asset_id, change_pos):
        json_bid_resp = bid_resp.json()
        player_club_id = json_bid_resp['auctionInfo'][0]['itemData']['id']
        data = '{"itemData":[{"id":%s,"pile":"club"}]}' % \
               (player_club_id)
        new_print(self.fifa_account, 'data =', data)
        # item send to club
        resp = put_item_for_sale(self.se, self.se_header, data, 0)
        json_resp = resp.json()
        try:
            reason = json_resp['itemData'][0]['reason']
            new_print(self.fifa_account, 'duplicate item')
            # self.se.get(f'{fifa_23_address}/item?idList=%s'%(player_club_id,), headers=self.header)
            payload = {"type": "player", "start": 0, "count": 21, "sort": "desc", "sortBy": "value",
                       "defId": str(asset_id)}
            resp = self.se.post(f'{fifa_23_address}/club', json=payload,
                                headers=self.se_header)
            json_resp = resp.json()
            dup_id = json_resp['itemData'][0]['id']
            data = '{"itemData":[{"id":%s,"pile":"club","swap":%s}]}' % \
                   (player_club_id, dup_id)
            resp = put_item_for_sale(self.se, self.se_header, data, 0)
            new_print(self.fifa_account, resp.text)

        except:
            pass
        # if str(json_bid_resp['auctionInfo'][0]['itemData']['preferredPosition']) != str(change_pos):
        #     self.buy_pos_change_and_apply(json_bid_resp['auctionInfo'][0]['itemData']['preferredPosition'], change_pos,
        #                                   player_club_id)

        # if accounts_sbc_id:
        #     current_sbc_process = SBCProcess.objects.filter(worker=self.sbc_worker, is_done=0).first()
        #     SBCProcessTarget.objects.create(sbc_process=current_sbc_process, club_id=player_club_id, position=position)

    def search_price(self, 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, team=0, link='',
                     max_tellorance=0):
        temp_link = ''
        try:
            last_price = price
            futbin_and_futwiz_price = 0
            if (not force_manual) or (not price):
                if not link:
                    price, updated_time, first_price, futbin_min_price, futbin_max_price = self.get_price_from_futbin_and_futwiz(
                        player_asset_id)
                    if price == 0:
                        price = last_price
                    else:
                        price = get_previous_price_grade(price)
                        futbin_and_futwiz_price = 1

                    # special just for sbc *****************
                    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
                price = 400
            # 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(player_asset_id, price, 'max_buy', rare=rare, pos=pos, team=team)
                json_resp = resp.json()
                auction_info = json_resp['auctionInfo']
                if len(auction_info) < 15:
                    futbin_and_futwiz_price = 0

            if price > limit_max_price:
                price = limit_max_price
            can_check_for_limit_max_price = 0
            if (not futbin_and_futwiz_price) or rare > 1 or force_manual:
                tellorance = 0
                while True:
                    if can_check_for_limit_max_price:
                        if price >= limit_max_price:
                            new_print(self.fifa_account, 'max price reached')
                            price = limit_max_price
                            break
                    if max_tellorance and tellorance > max_tellorance:
                        return 'high tellorance'
                    tellorance += 1
                    can_check_for_limit_max_price = 1
                    player_id = player_asset_id
                    if link:
                        temp_link = link + '&maxb=%s' % price
                    resp = self.search_player(player_id, price, 'max_buy', rare=rare, pos=pos, team=team,
                                              link=temp_link)
                    json_resp = resp.json()
                    auction_info = json_resp['auctionInfo']
                    new_print(self.fifa_account, 'price = ', price)
                    new_print(self.fifa_account, '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) < 10 and expire_check:
                        if max_check:
                            # price = get_next_price_grade(price)
                            break
                        if trade_mode == 2 and len(auction_info) > 0 and buy:
                            auction_info = auction_info[::-1]
                            data = '{"bid":%d}' % price
                            for trade in auction_info:
                                if price > 16000:
                                    # text = 'player price is more than 5000. will not buy this item . account = %s' % self.username
                                    # send_message(bot, 'critical', text)
                                    # time.sleep(300)
                                    new_print(self.fifa_account, 'player price more than 16000')
                                    break
                                else:
                                    new_print(self.fifa_account, 'data = ', data, 'in search price')
                                    # if trade['itemData']['preferredPosition'] == pos:
                                    check_resp = self.check_trade(trade['tradeId'])
                                    json_check_resp = check_resp.json()
                                    if json_check_resp['auctionInfo'][0]['tradeState'] != 'active':
                                        new_print(self.fifa_account, 'trade is closed')
                                        time.sleep(0.5)
                                        continue
                                    bid_resp = self.bid_trade(trade['tradeId'], data)
                                    new_print(self.fifa_account, 'bid_resp.content = ', bid_resp.text[:100])
                                    if (bid_resp.text != 'Permission Denied' and
                                            bid_resp.text != '' and
                                            bid_resp.text != 'You are not allowed to bid on this trade'):
                                        self.soft_ban_handler = 0
                                        self.account_sbc_targets_buy_staff(accounts_sbc_id, bid_resp, position,
                                                                           player_asset_id,
                                                                           change_pos)
                                        new_print(self.fifa_account, 'we bought this one')
                                        new_print(self.fifa_account, bid_resp.text)
                                        bought = 1
                                        break
                                    else:
                                        self.soft_ban_handler += 1
                                        if self.soft_ban_handler > 70:
                                            text = 'account %s temperory cant bid. deactivated' % self.fifa_account.user_name
                                            new_print(self.fifa_account, text)
                                            self.send_message(bot, 'critical', text)
                                            self.trade_worker.error_description = "temp cant bid"
                                            self.trade_worker.has_error = 1
                                            self.trade_worker.save()
                                            self.handle_end_bot()
                                            time.sleep(50)
                                        time.sleep(1.5)
                            if bought:
                                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)
                                    if link:
                                        temp_link = link + '&maxb=%s' % price
                                    resp = self.search_player(player_id, price_help, 'max_buy', rare=rare, pos=pos,
                                                              team=team, link=temp_link)
                                    json_resp = resp.json()
                                    auction_info = json_resp['auctionInfo']
                                    if len(auction_info) < 5 and expire_check:
                                        price = price_help
                                        for i in range(20):
                                            price_help = get_next_price_grade(price_help)
                                        if link:
                                            temp_link = link + '&maxb=%s' % price
                                        resp = self.search_player(player_id, price_help, 'max_buy', rare=rare, pos=pos,
                                                                  team=team, link=temp_link)
                                        json_resp = resp.json()
                                        auction_info = json_resp['auctionInfo']
                                        if len(auction_info) < 5 and expire_check:
                                            price = price_help

                                            for i in range(50):
                                                price_help = get_next_price_grade(price_help)
                                            if link:
                                                temp_link = link + '&maxb=%s' % price
                                            resp = self.search_player(player_id, price_help, 'max_buy', rare=rare,
                                                                      pos=pos, team=team, link=temp_link)
                                            json_resp = resp.json()
                                            auction_info = json_resp['auctionInfo']
                                            if len(auction_info) < 5 and expire_check:
                                                price = price_help

                                                for i in range(100):
                                                    price_help = get_next_price_grade(price_help)
                                                if link:
                                                    temp_link = link + '&maxb=%s' % price
                                                resp = self.search_player(player_id, price_help, 'max_buy', rare=rare,
                                                                          pos=pos, team=team, link=temp_link)
                                                json_resp = resp.json()
                                                auction_info = json_resp['auctionInfo']
                                                if len(auction_info) < 5 and expire_check:
                                                    price = price_help
                                    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:
                                    if link:
                                        temp_link = link + '&maxb=%s' % price
                                    resp = self.search_player(player_id, price_help, 'max_buy', rare=rare, pos=pos,
                                                              team=team, link=temp_link)
                                    json_resp = resp.json()
                                    auction_info = json_resp['auctionInfo']
                                    if len(auction_info) >= 5:
                                        price = price_help
                                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 = int(price)
            player_card.update_time = timezone.localtime()
            player_card.save()
            new_print(self.fifa_account, 'player_price = ', price)

            if trade_mode == 3:
                return price

            if trade_mode == 1:
                return price
                # 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 = int(price)
                # player_card.update_time = timezone.localtime()
                # player_card.save()
            #     cursor2.execute('select player_price from targets where player_asset_id = %s', (player_asset_id,))
            #     player_old_price = cursor2.fetchone()[0]
            #     cursor2.execute(
            #         'update targets set player_price = %s ,player_old_price = %s where player_asset_id = %s',
            #         (price, player_old_price, player_asset_id))
            #     conn2.commit()
            # elif trade_mode == 0:
            #     cursor2.execute('select player_price from invests where player_asset_id = %s', (player_asset_id,))
            #     player_old_price = cursor2.fetchone()[0]
            #     cursor2.execute(
            #         'update invests set player_price = %s ,player_old_price = %s where player_asset_id = %s',
            #         (price, player_old_price, player_asset_id))
            #     conn2.commit()

            # if trade_mode == 2:
            #     # sbc_target = SBCTarget.objects.filter(asset_id=player_asset_id)
            #     SBCTarget.objects.filter(asset_id=player_asset_id).update(price=price)
            #     # cursor2.execute('update sbc_targets set price = %s , update_time = %s where asset_id = %s',
            #     #                 (price, datetime.now(), player_asset_id))
            #     # conn2.commit()
            #     sbc_process = SBCProcess.objects.filter(worker=self.sbc_worker, is_done=False).first()
            #     sum_sbc_price = SBCTarget.objects.filter(sbc_type=sbc_process.sbc_type).aggregate(
            #         sum_price=Sum('price')).get('sum_price')
            #     # cursor2.execute('select sbc_id from accounts_sbc where id = %s', (accounts_sbc_id,))
            #     # sbc_id = cursor2.fetchone()[0]
            #     # cursor2.execute('select sum(price) from sbc_targets where sbc_id = %s', (sbc_id,))
            #     # sum_price = cursor2.fetchone()[0]
            #     new_print(self.fifa_account, 'sum actual price =', sum_sbc_price)
            #     sbc_process.sbc_type.refresh_from_db()
            #     sbc_process.sbc_type.sbc_actual_price = sum_sbc_price
            #     sbc_process.sbc_type.update_time = timezone.localtime()
            #     sbc_process.sbc_type.save()
            #     # cursor2.execute('update sbc set sbc_actual_price = %s where id = %s', (sum_price, sbc_id))
            #     # conn2.commit()
            #
            #     if not bought:
            #         return price

            if bought:
                return 'player bought'

        except:
            new_print(self.fifa_account, traceback.format_exc())
            self.get_new_sid()
            return 'sid'

    def put_item_in_auction_house(self, data):
        new_print(self.fifa_account, 'auction data = ', data)
        options_header = {'Accept': '*/*',
                          'Accept-Encoding': 'gzip, deflate, br',
                          'Accept-Language': 'en-US,en;q=0.5',
                          'Connection': 'keep-alive',
                          'Host': fifa_host,
                          'Access-Control-Request-Headers': 'content-type,x-ut-sid',
                          'Access-Control-Request-Method': 'POST',
                          'Origin': 'https://www.ea.com',
                          'Referer': 'https://www.ea.com/',
                          'User-Agent': user_agent
                          }
        self.se.options(
            f'{fifa_23_address}/auctionhouse',
            headers=options_header)
        resp = self.se.post(f'{fifa_23_address}/auctionhouse',
                            data=data,
                            headers=self.se_header)
        new_print(self.fifa_account, 'resp.content = ', resp.text[:100])
        return resp

    def item_put_for_sale(self, item_id, trade_id, win_price, start_price=0, buy_now_price=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(self.se, self.se_header, data, 0)
        new_print(self.fifa_account, 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=%s' % item_id
            resp = self.se.get(link, headers=self.se_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']
            max_price = js_resp[0]['maxPrice']
            if min_price > start_price and start_price < 30000:
                new_print(self.fifa_account, 'Min price is less than limit. Quick sell this item', min_price,
                          start_price)
                resp2 = self.se.delete(f'{fifa_23_address}/item/%s' % (item_id,),
                                       headers=self.se_header)
                new_print(self.fifa_account, resp2.text)
                time.sleep(randint(1, 3))
                return ''
            elif min_price > start_price and start_price > 30000:
                start_price = min_price
                buy_now_price = get_next_price_grade(min_price)

            if buy_now_price > max_price:
                buy_now_price = max_price
                start_price = get_previous_price_grade(buy_now_price)
            data = '{"itemData":{"id":%s},"startingBid":%d,"duration":3600,"buyNowPrice":%d}' % (
                item_id, start_price, buy_now_price)
            sell_resp = self.put_item_in_auction_house(data)
            if sell_resp.text:
                self.win_controller_count += 1
                self.temp_win_controller += 1
            else:
                text = 'problem in listing. account : %s' % self.fifa_account.user_name
                self.send_message(bot, -1001444245007, text)
        time.sleep(randint(1, 3))
        try:
            return sell_resp
        except:
            pass

    # def sell_success_bid(self, trade_id, start_price, buy_now_price, expires, log_object: TradeLog):
    #     new_print(self.fifa_account, 'start thread after ', int(expires) + 60, ' sleep sec')
    #     connection.close()
    #     time.sleep(int(expires) + 60)
    #     json_check_resp = self.check_trade(trade_id).json()
    #     trade_info = json_check_resp['auctionInfo'][0]
    #     new_print(self.fifa_account, 'trade complete information : ', trade_info['bidState'], trade_info['currentBid'])
    #     if trade_info and trade_info['bidState'] == "highest":
    #         log_object.sell_time = timezone.localtime()
    #         log_object.sell_price = buy_now_price
    #         log_object.bid_success = True
    #         log_object.save()
    #         new_print(self.fifa_account, 'bid was success , try to sell it')
    #         self.item_put_for_sale(trade_info['itemData']['id'], trade_info['tradeId'], 0,
    #                                start_price=start_price,
    #                                buy_now_price=buy_now_price)
    #     else:
    #         new_print(self.fifa_account, 'bid failed')
    #         clear_outbid(self.fifa_account, self.se, self.se_header, trade_info['tradeId'])

    def sell_success_bid(self, log_object: TradeLog):
        start_price = log_object.start_price
        buy_now_price = log_object.buy_now_price
        new_print(log_object.fifa_account, 'start bot to complete trade : ', log_object)
        self.logout_login(self.fifa_account)
        json_check_resp = self.check_trade(log_object.trade_id).json()
        if json_check_resp.get('reason', '') == 'expired session':
            self.get_new_sid()
            json_check_resp = self.check_trade(log_object.trade_id).json()
        if json_check_resp.get('auctionInfo'):
            trade_info = json_check_resp['auctionInfo'][0]
            new_print(self.fifa_account, 'trade complete information : ', trade_info['bidState'],
                      trade_info['currentBid'])
        else:
            new_print(self.fifa_account, 'trade info wrong : ', json_check_resp)
            trade_info = {}
        if trade_info and trade_info['bidState'] == "highest":
            log_object.refresh_from_db()
            log_object.sell_time = timezone.localtime()
            log_object.sell_price = buy_now_price
            log_object.bid_success = 1
            log_object.status = 2
            log_object.save()
            new_print(self.fifa_account, 'bid was success , try to sell it')
            self.item_put_for_sale(trade_info['itemData']['id'], trade_info['tradeId'], 0,
                                   start_price=start_price,
                                   buy_now_price=buy_now_price)
        else:
            new_print(self.fifa_account, 'bid failed')
            clear_outbid(self.fifa_account, self.se, self.se_header, trade_info['tradeId'])
            log_object.status = 4
            log_object.save()

    def check_single_player_bid_again(self, log_object: TradeLog):
        new_print(log_object.fifa_account, 'start check trade : ', log_object)
        self.logout_login(self.fifa_account)
        trade_id = log_object.trade_id
        check_resp = self.check_trade(trade_id)
        json_check_resp = check_resp.json()
        if json_check_resp.get('reason', '') == 'expired session':
            self.get_new_sid()
            json_check_resp = self.check_trade(log_object.trade_id).json()
        if json_check_resp.get('auctionInfo'):
            trade_info = json_check_resp['auctionInfo'][0]
            new_print(self.fifa_account, 'trade complete information : ', trade_info['bidState'],
                      trade_info['currentBid'])
        else:
            new_print(self.fifa_account, 'trade info wrong : ', json_check_resp)
            trade_info = {}
        if trade_info and trade_info['bidState'] == "highest":
            if trade_info['currentBid'] < log_object.single_player_trade_worker.max_bid_price:
                data = '{"bid":%d}' % log_object.single_player_trade_worker.max_bid_price
                self.bid_trade(trade_id, data)

    def search_player_and_bid(self, player_asset_id, player_bid_price, number_of_bids, trade_mode=1, max_bid_price=0,
                              position=0, accounts_sbc_id=0, pos='', change_pos='', sbc_target_id=0, team=0,
                              player_sell_price=0, player_sell_now_price=0, search_filter_type='max_bid',
                              pages_count=30, result_number='21'):
        """

        @param player_asset_id:
        @param player_bid_price:
        @param number_of_bids:
        @param trade_mode:
        @param max_bid_price:
        @param position:
        @param accounts_sbc_id:
        @param pos:
        @param change_pos:
        @param sbc_target_id:
        @param team:
        @param player_sell_price:
        @param player_sell_now_price_grade:
        @param search_filter_type: if this field is empty don`t search with any mode.
        @param pages_count: counts of page must search.
        @param result_number: number of result searching. request result per page.
        @return:
        """
        start = 0
        bought_trade = {}
        done = 0
        temp_number_of_bids = 0
        last_expire = 0
        if trade_mode == 1:
            expire_time = 3600
        elif trade_mode == 0:
            expire_time = 600
        elif trade_mode == 2:
            expire_time = 99999999
        elif trade_mode == 3:
            expire_time = 99999999
        while True:
            if (trade_mode == 0) and self.job_time_id:
                if self.remaining_buys < 0:
                    self.handle_end_bot()
                    time.sleep(60)
            if start >= pages_count * 20:
                new_print(self.fifa_account, 'no more try')
                break
            if temp_number_of_bids > number_of_bids:
                new_print(self.fifa_account, 'tmp number of bids > number of bids')
                break
            new_print(self.fifa_account, 'search and bid for %s bids' % str(start + 20))
            new_print(self.fifa_account, 'temp_number_of_bids = ', temp_number_of_bids)
            resp = self.search_player(player_asset_id, get_previous_price_grade(player_bid_price), search_filter_type,
                                      start=str(start), team=team, number=result_number)
            json_resp = resp.json()
            trades = json_resp['auctionInfo']
            new_print(self.fifa_account, 'want player bid price : ', player_bid_price)
            if not trades:
                new_print(self.fifa_account, 'player has not trades with this price. expire time 1 hour next , ',
                          player_asset_id, player_bid_price)
                sleep_time = 60 * 60
                if player_bid_price < 300:
                    sleep_time = 60 * 60 * 6
                # player_card = PlayerCard.objects.filter(asset_id=player_asset_id, use_on_trade=True).first()
                # player_card.trade_last_bid_time = timezone.localtime() + timezone.timedelta(seconds=sleep_time)
                # player_card.save()
                last_expire = sleep_time
                break
            for trade_item in trades:
                new_print(self.fifa_account, 'trade item data : ',
                          trade_item['currentBid'], trade_item['startingBid'], trade_item['expires'])
                if trade_item['expires'] > expire_time:
                    new_print(self.fifa_account, 'remaining trades are more than %d seconds' % expire_time)
                    done = 1
                    break
                else:
                    last_expire = trade_item['expires']
                self.trade_worker.refresh_from_db()
                if self.trade_worker.has_error:
                    return None, last_expire
                if trade_mode not in [2, 3]:
                    bid_this_one = 0
                    temp_bid_price = player_bid_price
                    if trade_item['startingBid'] <= player_bid_price and trade_item['currentBid'] < player_bid_price:
                        bid_this_one = 1
                    elif trade_item['startingBid'] <= max_bid_price and trade_item['currentBid'] < max_bid_price:
                        bid_this_one = 1
                        temp_bid_price = max_bid_price
                else:
                    bid_this_one = 1
                    temp_bid_price = trade_item['buyNowPrice']
                if bid_this_one:
                    data = '{"bid":%d}' % temp_bid_price
                    if self.bid_controller_count < 30:

                        if trade_item['bidState'] == "highest":
                            new_print(self.fifa_account, 'I already have highest offer on this trade')
                            continue

                        self.update_credit()
                        time.sleep(1)
                        self.fifa_account.refresh_from_db()
                        if self.fifa_account.credit < temp_bid_price:
                            new_print(self.fifa_account, 'not enough credit.w8 5 minutes.')
                            return 'low credit', trade_item['expires']
                        new_print(self.fifa_account, 'data = ', data)
                        check_resp = self.check_trade(trade_item['tradeId'])
                        json_check_resp = check_resp.json()
                        try:
                            if json_check_resp['auctionInfo'][0]['tradeState'] != 'active':
                                new_print(self.fifa_account, 'trade is closed')
                                time.sleep(0.5)
                                continue
                            if int(json_check_resp['auctionInfo'][0].get('currentBid', 0)) >= temp_bid_price:
                                new_print(self.fifa_account, 'bid is higher than my bid ',
                                          temp_bid_price,
                                          json_check_resp['auctionInfo'][0].get('currentBid', 0))
                                time.sleep(0.5)
                                continue
                        except KeyError:
                            new_print(self.fifa_account, 'can not find key : ', json_resp)
                        bid_resp = self.bid_trade(trade_item['tradeId'], data)
                        new_print(self.fifa_account, 'bid_resp = ', bid_resp.text[:100])
                        if bid_resp.text == 'Watchlist is full':
                            new_print(self.fifa_account, 'watchlist is full')
                            return 'Watchlist is full', trade_item['expires']
                        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)):
                            new_print(self.fifa_account, 'bid has error : ', bid_resp.text)
                            continue
                        player_card = PlayerCard.objects.filter(asset_id=player_asset_id).first()
                        player_sell_start_price = get_previous_price_grade(player_sell_price)
                        item_sell_now_price = player_sell_price
                        if player_sell_now_price:
                            item_sell_now_price = player_sell_now_price
                        if isinstance(self.trade_worker, TradeWorker):
                            TradeLog.objects.create(
                                bid_price=int(player_bid_price),
                                player_card=player_card,
                                trade_worker=self.trade_worker,

                                trade_id=trade_item['tradeId'],
                                start_price=player_sell_start_price,
                                fifa_account=self.fifa_account,
                                buy_now_price=item_sell_now_price,
                                status=0,
                                expires=timezone.localtime() + timezone.timedelta(seconds=int(trade_item['expires']))
                            )
                        if isinstance(self.trade_worker, SinglePlayerTradeWorker):
                            TradeLog.objects.create(
                                bid_price=int(player_bid_price),
                                player_card=player_card,
                                single_player_trade_worker=self.trade_worker,

                                trade_id=trade_item['tradeId'],
                                start_price=player_sell_start_price,
                                fifa_account=self.fifa_account,
                                buy_now_price=item_sell_now_price,
                                status=0,
                                expires=timezone.localtime() + timezone.timedelta(seconds=int(trade_item['expires']))
                            )

                        self.bid_controller_count += 1
                        self.temp_bid_controller += 1
                        temp_number_of_bids += 1
                        if temp_number_of_bids >= number_of_bids:
                            new_print(self.fifa_account, 'bid completed')
                            done = 1
                            break
                        time.sleep(randint(1, 3))
                    else:
                        new_print(self.fifa_account,
                                  'number of bids will be more than standard bid number. I wont bid')
                        return 'high bid', last_expire
            if done:
                break
            start += 20
            if trade_mode == 2 or trade_mode == 3:
                break
            # time.sleep(1)
        if temp_number_of_bids < number_of_bids:
            self.weak_target_controller_count += 1
        if trade_mode == 3:
            if done == 1:
                return bought_trade, last_expire
            else:
                return False, last_expire
        return None, last_expire

    def start_trade(self):
        if not self.trade_worker.status:
            self.trade_worker.status = 'preparing ...'
            self.trade_worker.last_run_time = timezone.localtime()
            self.trade_worker.save()
        new_print(self.fifa_account, '## ' * 100)
        new_print(self.fifa_account, 'Trade Bot started')

        self.logout_login(self.fifa_account)
        self.sell_items(self.fifa_account)
        try:
            # self.update_credit()
            new_credit = self.get_plus_credit()
            self.trade_worker.last_update_coin = int(new_credit)
            self.trade_worker.save()
        except:
            pass
        time.sleep(1)
        if self.trade_worker.start_coin == 0:
            credit = self.get_plus_credit()
            self.trade_worker.start_coin = int(credit)
            self.trade_worker.save()
            self.trade_worker.refresh_from_db()

        is_done = False
        for item in range(100):
            self.trade_worker.refresh_from_db()
            if is_done is True:
                new_print(self.fifa_account, 'trade bot stopped ....')
                break
            if self.trade_worker.has_error:
                new_print(self.fifa_account, 'trade bot stopped .......')
                break
            player_target = self.get_new_player_target()
            if player_target is None:
                new_print(self.fifa_account, 'No Target Found')
                break
            player_target.trade_is_working = True
            player_target.save()
            player_target.refresh_from_db()
            search_number = self.fifa_account.account_search.filter(
                search_time__gt=timezone.localtime() - timezone.timedelta(hours=24)).count()
            if search_number > 200:
                self.trade_worker.refresh_from_db()
                self.trade_worker.has_error = 1
                self.trade_worker.error_description = 'high search'
                self.trade_worker.is_done = 1
                self.trade_worker.save()
                break
            for i in range(10):
                if is_done is True:
                    break
                price = self.search_price(price=0,
                                          player_asset_id=player_target.asset_id,
                                          trade_mode=1,
                                          # position=player_target.position or 0,
                                          # accounts_sbc_id=accounts_sbc_id,
                                          # change_pos=change_pos,
                                          force_manual=1,
                                          team=player_target.team,
                                          max_tellorance=8)
                if str(price) == 'sid':
                    new_print(self.fifa_account, 'session expired , price is : ', price)
                    break
                if str(price) == 'high tellorance':
                    new_print(self.fifa_account, 'high tellorance , price is : ', price)
                    player_target.trade_last_bid_time = timezone.localtime() + timezone.timedelta(seconds=60 * 60 * 6)
                    player_target.trade_is_working = False
                    player_target.save()
                    player_target.refresh_from_db()
                    break
                yesterday_price = self.get_yesterday_price(player_target.asset_id)
                new_print(self.fifa_account, 'yesterday price ', yesterday_price, ' now price ', price)
                gp_p = get_previous_price_grade
                gp_n = get_next_price_grade
                if yesterday_price and not (
                        gp_p(gp_p(gp_p(gp_p(gp_p(gp_p(gp_p(yesterday_price))))))) <=
                        int(price)
                        <= gp_n(gp_n(gp_n(gp_n(gp_n(gp_n(gp_n(yesterday_price)))))))):
                    new_print(self.fifa_account, 'player not balance : ', yesterday_price, price)
                    player_target.trade_last_bid_time = timezone.localtime() + timezone.timedelta(seconds=60 * 60)
                    player_target.trade_is_working = False
                    player_target.save()
                    player_target.refresh_from_db()
                    break
                try:
                    max_bid_price = get_round_price(price - (price * .05))
                    if ((price - (price * .05)) - max_bid_price) < 40:
                        new_print(self.fifa_account, 'profit is less than 40',
                                  ((price - (price * .05)) - max_bid_price))
                        max_bid_price = get_previous_price_grade(max_bid_price)
                    number_of_bids = 30
                    sell_price = get_next_price_grade(price)
                    result = self.search_player_and_bid(
                        player_target.asset_id, max_bid_price, number_of_bids,
                        trade_mode=1, max_bid_price=0, position=0, accounts_sbc_id=0,
                        pos='', change_pos='', sbc_target_id=0, team=0,
                        player_sell_price=sell_price)
                    player_target.refresh_from_db()
                    if result[0] == 'Watchlist is full':
                        is_done = True
                        player_target.trade_is_working = False
                        player_target.trade_last_bid_time = timezone.localtime() + timezone.timedelta(seconds=result[1])
                        player_target.save()
                    elif result[0] == 'low credit':
                        is_done = True
                        player_target.trade_is_working = False
                        player_target.trade_last_bid_time = timezone.localtime() + timezone.timedelta(seconds=result[1])
                        player_target.save()
                    elif result[0] == 'high bid':
                        is_done = True
                        player_target.trade_is_working = False
                        player_target.trade_last_bid_time = timezone.localtime() + timezone.timedelta(seconds=result[1])
                        player_target.save()
                    else:
                        player_target.trade_is_working = False
                        if result[1] == 0:
                            player_target.trade_last_bid_time = timezone.localtime() + timezone.timedelta(
                                seconds=60 * 60)
                        else:
                            player_target.trade_last_bid_time = timezone.localtime() + timezone.timedelta(
                                seconds=int(result[1]))
                        player_target.save()
                    break
                except:
                    new_print(self.fifa_account, 'trace back in run trade : ', traceback.format_exc())

        close_old_connections()

    def start_trade_single_player(self):
        if not self.trade_worker.status:
            self.trade_worker.status = 'preparing ...'
            self.trade_worker.last_run_time = timezone.localtime()
            self.trade_worker.save()
        new_print(self.fifa_account, '## ' * 100)
        new_print(self.fifa_account, 'Trade Bot started')

        # todo : set logout_login result and check if login success do other things
        self.logout_login(self.fifa_account)
        try:
            result = self.se.put(f'{fifa_23_address}/auctionhouse/relist',
                                 headers=self.se_header)
            new_print(self.fifa_account, 'relist items result : ', result.status_code, result.text)
        except:
            new_print(self.fifa_account, 'error on relist : ', traceback.format_exc())

        try:
            # self.update_credit()
            new_credit = self.get_plus_credit()
            self.trade_worker.last_update_coin = int(new_credit)
            self.trade_worker.save()
        except:
            pass
        time.sleep(1)
        if self.trade_worker.start_coin == 0:
            credit = self.get_plus_credit()
            self.trade_worker.start_coin = int(credit)
            self.trade_worker.save()
            self.trade_worker.refresh_from_db()

        is_done = False
        # for item in range(100):
        # self.trade_worker.refresh_from_db()
        # if self.trade_worker.has_error:
        #     is_done = True
        # if is_done is True:
        #     new_print(self.fifa_account, 'trade bot stopped ....')
        #     break
        # if self.trade_worker.has_error:
        #     new_print(self.fifa_account, 'trade bot stopped .......')
        #     break
        player_target = self.trade_worker.player_card
        search_number = self.fifa_account.account_search.filter(
            search_time__gt=timezone.localtime() - timezone.timedelta(hours=24)).count()
        if search_number > 200:
            self.trade_worker.refresh_from_db()
            self.trade_worker.has_error = 1
            self.trade_worker.error_description = 'high search'
            self.trade_worker.is_done = 1
            self.trade_worker.save()
            # break
        for i in range(10):
            self.trade_worker.refresh_from_db()
            if self.trade_worker.has_error:
                is_done = True
            if is_done is True:
                break
            try:
                max_bid_price = self.trade_worker.max_bid_price
                number_of_bids = 30
                sell_now_price = get_round_price(random.randint(
                    self.trade_worker.start_sell_now_price,
                    self.trade_worker.end_sell_now_price)
                )
                result = self.search_player_and_bid(
                    player_target.asset_id, max_bid_price, number_of_bids,
                    trade_mode=1, max_bid_price=0, position=0, accounts_sbc_id=0,
                    pos='', change_pos='', sbc_target_id=0, team=0, search_filter_type='',
                    player_sell_price=get_next_price_grade(self.trade_worker.sell_start_price),
                    player_sell_now_price=sell_now_price,
                    pages_count=1, result_number='50',
                )
                if result[0] == 'Watchlist is full':
                    self.trade_worker.refresh_from_db()
                    self.trade_worker.used_fifa_accounts.add(self.fifa_account)
                    self.trade_worker.unused_fifa_accounts.remove(self.fifa_account)
                    self.trade_worker.save()
                    is_done = True
                elif result[0] == 'low credit':
                    self.trade_worker.refresh_from_db()
                    self.trade_worker.used_fifa_accounts.add(self.fifa_account)
                    self.trade_worker.unused_fifa_accounts.remove(self.fifa_account)
                    self.trade_worker.save()
                    is_done = True
                break
            except:
                new_print(self.fifa_account, 'trace back in run trade : ', traceback.format_exc())
        new_print(self.fifa_account, 'trade bot stopped .......')

    def get_price_graph(self, asset_id):
        link = f'https://www.futbin.com/24/playerGraph?type=daily_graph&year=23&player={asset_id}&set_id='
        resp = self.use_cloud_scraper(link)
        try:
            # json_resp = resp.json()
            json_resp = json.loads(resp)
        except:
            new_print(self.fifa_account, 'can not get graph price from futbin : ', resp.text)
            json_resp = {}
        return json_resp

    def get_yesterday_price(self, asset_id):
        result = self.get_price_graph(asset_id)
        try:
            price = result.get('ps')[-1][1]
        except:
            new_print(self.fifa_account, 'can not get yesterday price from futbin : ', result)
            price = 0
        return price

    def get_new_player_target(self):
        player_card = PlayerCard.objects.filter(
            use_on_trade=True,
            trade_is_working=False,
            trade_last_bid_time__lt=timezone.localtime() - timezone.timedelta(seconds=60 * 10)
        ).first()
        if not player_card:
            player_card = PlayerCard.objects.filter(
                use_on_trade=True,
                trade_last_bid_time__lt=timezone.localtime() - timezone.timedelta(seconds=60 * 60)
            ).first()
            if player_card:
                player_card.trade_last_bid_time = timezone.localtime()
                player_card.save()
            # else:
            #     player_card = PlayerCard.objects.filter(
            #         use_on_trade=True,
            #         # trade_is_working=False
            #     ).order_by('trade_last_bid_time').first()
        else:
            player_card.trade_last_bid_time = timezone.localtime()
            player_card.save()
        return player_card

    def handle_end_bot(self, without_update_time=0):
        self.trade_worker.must_done = True
        self.trade_worker.save()
        self.fifa_account.refresh_from_db()
        new_print(self.fifa_account, 'inside handle end bot')
        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()
        if not without_update_time:
            self.trade_worker.last_run_time = timezone.localtime()
            self.trade_worker.save()
        try:
            self.web_driver.close()
            if os.name == 'nt':
                os.system("TASKKILL /F /IM chromedriver.exe")
        except:
            pass
        if os.name != 'nt':
            try:
                shutil.rmtree("%s/user_data/%s" % (os.path.join(BASE_DIR, 'accounts'), self.fifa_account.user_name))
            except:
                pass
        # os.remove('%s/user_data/%s' % (file_path, self.username))
        # data = {'terminate': True,
        #         'signal': 'SIGKILL'}
        # link = '/api/task/revoke/{}?terminate=true'.format(self.trade_worker.task_id)
        # api_root = FLOWER_ADDRESS
        new_print(self.fifa_account, 'before revoking task ...')
        if os.name != 'nt':
            try:
                app.control.revoke(self.trade_worker.task_id, terminate=True, signal='SIGKILL')
            except:
                new_print(self.fifa_account, 'no app found to kill will revoking ...')
        # requests.post(api_root + link, data=data)
        time.sleep(3)
        if os.name == 'nt':
            self.public_moves.put_on_rest_mode()
            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")

        new_print(self.fifa_account, 'after handle end bot')
        time.sleep(100)
        raise Exception('After Handle End Bot')

    def send_message(self, bot, chat_id, text):
        try:
            # data = {'text': text}
            new_print(self.fifa_account, 'sending on telegram')
            new_print(self.fifa_account, text)
            # text += '\nserver address:\n%s' % server_address

            chat_id = -1001575820673

            # res = requests.post('https://tbb.cloud.mattermost.com/hooks/%s'%chat_id, data=json.dumps(data))
            # print res.text
            # print 'not send this message to telegram'
            if os.name != 'nt':
                chat_id = -1001712554408
                bot.sendMessage(chat_id, text)
            else:
                print(text)
        except:
            new_print(self.fifa_account, 'except in send message')
            new_print(self.fifa_account, traceback.format_exc())

    def logout_login(self, fifa_account: FifaAccount, use_new_sid=True):
        # set_sub_log(sbc_worker, 'logout login staff')
        try:
            self.web_driver.close()
            if os.name == 'nt':
                os.system("TASKKILL /F /IM chromedriver.exe")
        except:
            pass
        fifa_backup = fifa_account.account_backup_code.first()
        # cursor2.execute('select account_backup,app_auth from accounts where account_email = %s', (self.username,))
        backup_code = fifa_backup.backup_code
        app_auth = fifa_backup.app_code
        self.proxy_ip, self.proxy_port, self.proxy_user, self.proxy_pass, proxy_id, self.se = self.set_proxy(
            self.fifa_account.id, self.se)
        for ni in range(85):
            fifa_account.refresh_from_db()
            if (fifa_account.login_working == 0 or
                    fifa_account.last_login_time < timezone.localtime() - timezone.timedelta(seconds=240)
            ):
                fifa_account.login_working = 1
                fifa_account.last_login_time = timezone.localtime()
                fifa_account.save()
                break
            else:
                time.sleep(3)

        if fifa_account.access_token and fifa_account.nucleus_id and use_new_sid:
            try:
                if self.get_new_sid_by_access_token(sid=fifa_account.sid):
                    new_print(self.fifa_account, 'old sid is alive')
                    fifa_account.login_working = 0
                    fifa_account.save()
                    return True
                else:
                    new_print(self.fifa_account, 'old sid is done , generate new.')
                if self.get_new_sid_by_access_token():
                    time.sleep(0.5)
                    if self.running_platform == 'console':
                        self.update_credit()
                    else:
                        self.check_account_web_app()
                    time.sleep(0.5)
                    fifa_account.login_working = 0
                    fifa_account.save()
                    return True
            except:
                new_print(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.cookies
        if cookies:
            cookies = ast.literal_eval(cookies)
        try:
            new_print(fifa_account, 'proxy data = ', self.proxy_ip, self.proxy_port, self.proxy_user, self.proxy_pass,
                      proxy_id)
            # TODO :  fix this
            # if os.name == 'nt':
            #     proxy_ip = proxy_port = proxy_user = proxy_pass = ''
            new_print(fifa_account, 'proxy_data = ', self.proxy_ip, self.proxy_port, self.proxy_user, self.proxy_pass)
            self.web_driver, self.futbin_cookies, need_to_close_ultimate_in_console, need_to_create_club = login_to_account(
                self.fifa_account.user_name, self.fifa_account.password, backup_code, proxy_ip=self.proxy_ip,
                proxy_port=self.proxy_port,
                proxy_user=self.proxy_user,
                proxy_pass=self.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.web_driver.close()
                if os.name == 'nt':
                    os.system("TASKKILL /F /IM chromedriver.exe")
                # self.public_moves.console_open_ultimate()
                # self.console_close_ultimate()
                # self.web_driver, self.futbin_cookies, need_to_close_ultimate_in_console, need_to_create_club = login_to_account(
                #     self.fifa_account.user_name, self.fifa_account.password, '', use_proxy=1,
                #     proxy_ip=self.proxy_ip,
                #     proxy_port=self.proxy_port, proxy_user=self.proxy_user,
                #     proxy_pass=self.proxy_pass, app_auth=self.app_auth, cookies=cookies
                # )
            new_print(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(fifa_account, 'need ro create club from logout login')
                self.web_driver.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")

            new_print(fifa_account, 'after login', timezone.localtime())


        except:
            new_print(fifa_account, traceback.format_exc())
            new_print(fifa_account, 'problem in login')
            fifa_account.login_working = 0
            fifa_account.save()
            self.handle_end_bot()
            return
        checker = 1
        try:
            if self.web_driver == 'proxy dead':
                text = 'proxy %s is dead for ea' % self.proxy_ip
                new_print(fifa_account, 'text = ', text)
                try:
                    FifaProxy.objects.get(id=proxy_id).delete()
                except:
                    pass
                self.send_message(bot, 'critical', text)
                self.handle_end_bot(without_update_time=1)
                time.sleep(50)

            # if (self.web_driver == 'bad_information' or
            #         self.web_driver == '' or
            #         self.web_driver == 'banned' or
            #         self.web_driver == 'app_code_active' or
            #         self.web_driver == 'bad_backup'):
            if (self.web_driver 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.web_driver == 'banned':
                    text = 'Your account has been disabled %s' % self.fifa_account.user_name
                    fifa_account.refresh_from_db()
                    fifa_account.delete_club_number = 13
                    fifa_account.save()
                    new_print(fifa_account, text)
                    self.trade_worker.error_description = "account disabled"
                    self.trade_worker.has_error = 1
                    self.trade_worker.save()
                elif self.web_driver == 'bad_backup':
                    text = 'bad backup code %s' % self.fifa_account.user_name
                    new_print(fifa_account, text)
                    if self.trade_worker.running_platform == 'console':
                        self.trade_worker.status = 'bad_backup'
                        self.trade_worker.status_change_time = timezone.localtime()
                        self.trade_worker.description = ''
                        self.trade_worker.save()
                        time.sleep(1000)
                    self.trade_worker.error_description = "bad backup code"
                    self.trade_worker.has_error = 1
                    self.trade_worker.save()
                else:
                    new_print(fifa_account, 'bad information try 1 more time ... . driver is : ',
                              self.web_driver)
                    self.proxy_ip, self.proxy_port, self.proxy_user, self.proxy_pass, proxy_id, self.se = self.set_proxy(
                        self.fifa_account.id, self.se, change=1)
                    # TODO : fix this
                    # if os.name == 'nt':
                    #     proxy_ip = proxy_port = proxy_user = proxy_pass = prooxy_id = ''
                    new_print(fifa_account, 'proxy_data = ', self.proxy_ip, self.proxy_port, self.proxy_user,
                              self.proxy_pass)
                    self.web_driver, self.futbin_cookies, need_to_close_ultimate_in_console, need_to_create_club = login_to_account(
                        self.fifa_account.user_name, self.fifa_account.password, backup_code, proxy_ip=self.proxy_ip,
                        proxy_port=self.proxy_port,
                        proxy_user=self.proxy_user, proxy_pass=self.proxy_pass,
                        app_auth=app_auth, cookies=cookies)
                    if need_to_close_ultimate_in_console and self.running_platform == 'console':
                        self.web_driver.close()
                        if os.name == 'nt':
                            os.system("TASKKILL /F /IM chromedriver.exe")
                        # self.public_moves.console_open_ultimate()
                        # self.console_close_ultimate()
                        self.web_driver, self.futbin_cookies, need_to_close_ultimate_in_console, need_to_create_club = login_to_account(
                            self.fifa_account.user_name, self.fifa_account.password, backup_code,
                            proxy_ip=self.proxy_ip,
                            proxy_port=self.proxy_port,
                            proxy_user=self.proxy_user, proxy_pass=self.proxy_pass,
                            app_auth=app_auth, cookies=cookies)
                    if need_to_create_club and self.running_platform == 'console':
                        new_print(fifa_account, 'need ro create club from logout login 2')
                        self.web_driver.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.web_driver, self.futbin_cookies, need_to_close_ultimate_in_console, need_to_create_club = login_to_account(
                            self.fifa_account.user_name, self.fifa_account.password, backup_code,
                            proxy_ip=self.proxy_ip,
                            proxy_port=self.proxy_port,
                            proxy_user=self.proxy_user, proxy_pass=self.proxy_pass,
                            app_auth=app_auth, cookies=cookies)

                    # if (self.web_driver == 'bad_information' or
                    #         self.web_driver == '' or
                    #         self.web_driver == 'banned' or
                    #         self.web_driver == 'app_code_active' or
                    #         self.web_driver == 'bad_backup'):
                    if (self.web_driver in [
                            'bad_information', '', 'banned', 'app_code_active', 'bad_backup', 'early_access',
                            'need_reset_password']
                        ):
                        new_print(fifa_account, 'bad information , driver : ', self.web_driver)
                        text = 'cant login to account %s' % self.fifa_account.user_name
                        self.trade_worker.refresh_from_db()
                        self.trade_worker.error_description = "cant login"
                        self.trade_worker.status = 'login failed'
                        self.trade_worker.status_change_time = timezone.localtime()
                        self.trade_worker.save()
                        self.trade_worker.refresh_from_db()
                        if self.running_platform != 'console':
                            self.trade_worker.has_error = 1
                            self.trade_worker.save()
                        else:
                            new_print(fifa_account, 'waiting for fixing login data and running again ...')
                            time.sleep(1000)
                    else:
                        checker = 1
                        new_print(fifa_account, 'login successful', timezone.localtime())
                        fifa_account.refresh_from_db()
                        fifa_account.cookies = str(self.web_driver.get_cookies())
                        fifa_account.save()
                if text:
                    new_print(fifa_account, 'text = ', text)
                    self.send_message(bot, 'critical', text)
                    fifa_account.login_working = 0
                    fifa_account.save()
                    self.handle_end_bot()
                    return text
            else:
                checker = 1
                new_print(fifa_account, 'login successful', timezone.localtime())
                fifa_account.refresh_from_db()
                fifa_account.cookies = str(self.web_driver.get_cookies())
                fifa_account.save()
        except:
            new_print(fifa_account, "self.web_driver = ", self.web_driver)
            new_print(fifa_account, traceback.format_exc())
            new_print(fifa_account, 'login failed')
            checker = 0
        if checker:
            try:
                new_print(fifa_account, 'setting cookies')
                for cookie in self.futbin_cookies:
                    self.se2.cookies.set(cookie['name'], cookie['value'])
                new_print(fifa_account, 'setting proxy')
                if self.proxy_ip:
                    proxies = {'https': 'http://%s:%s@%s:%s' % (
                        self.proxy_user, self.proxy_pass, self.proxy_ip, self.proxy_port)}
                    self.se2.proxies.update(proxies)

                    self.proxy_ip = self.proxy_ip
                    self.proxy_port = self.proxy_port
                    self.proxy_user = self.proxy_user
                    self.proxy_pass = self.proxy_pass
                else:
                    self.proxy_ip = self.proxy_port = self.proxy_user = self.proxy_pass = ''
                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.web_driver, special='break')
                new_print(fifa_account, 'check for captcha')
                if not elem:
                    captcha = self.check_captcha()
                    if captcha:
                        self.get_new_sid()

                    else:
                        # elem = wait_for_element('xpath', 'one', "//button[contains(text(),'Continue')]",
                        #                         special='fast_break',
                        #                         driver=self.web_driver)
                        # if elem:
                        #     while True:
                        #         elem = wait_for_element('xpath', 'one', "//button[contains(text(),'Continue')]",
                        #                                 special='break', driver=self.web_driver)
                        #         if elem:
                        #             self.custome_click(elem)
                        #         else:
                        #             break
                        pass
                new_print(fifa_account, 'check for captcha completed ...')
                self.sid = self.web_driver.execute_script(
                    "return services.Authentication.sessionUtas.id")
                self.fifa_account.refresh_from_db()
                self.fifa_account.sid = self.sid
                self.fifa_account.save()
                self.nucleus_id = self.web_driver.execute_script(
                    "return services.User.getUser().id")
                # persona = driver.execute_script("return services.User.getUser().personas._collection")
                platforms_skus = {'ps': ['FFA23PS4', 'FFA23PS5'], 'xbox360': ['FFA23XBO'], 'xboxs': ['FFA23XSX']}
                persona = self.web_driver.execute_script(
                    "return services.User.getUser().personas[0]['id']")
                new_print(fifa_account, 'check for skus')
                try:
                    for i in range(100):
                        skus = self.web_driver.execute_script(
                            "return services.User.getUser().personas[%s]['_sku']" % i)
                        new_print(fifa_account, 'skus = ', skus)
                        if skus in platforms_skus.get(self.fifa_account.platform, []):
                            persona = self.web_driver.execute_script(
                                "return services.User.getUser().personas[%s]['id']" % i)
                            new_print(fifa_account, 'skus match. persona = ', persona)
                            break
                except:
                    new_print(fifa_account, 'no skus for fifa 23')
                try:
                    for i in range(100):
                        skus = self.web_driver.execute_script(
                            "return services.User.getUser().personas[%s]['_sku']" % i)
                        new_print(fifa_account, 'skus = ', skus)
                        if skus == "FFA22PS4" or skus == 'FFA22PS5' or skus == 'FFA22XBO' or skus == 'FFA22XSX':
                            persona = self.web_driver.execute_script(
                                "return services.User.getUser().personas[%s]['id']" % i)
                            new_print(fifa_account, 'skus match. persona = ', persona)
                            break
                except:
                    new_print(fifa_account, 'no skus for fifa 22')

                persona = str(persona)
                access_token = self.web_driver.execute_script(
                    "return window.localStorage.getItem('_eadp.identity.access_token')")
                new_print(fifa_account, 'access_token = ', access_token)
                fifa_account.refresh_from_db()
                fifa_account.access_token = access_token
                fifa_account.nucleus_id = self.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(fifa_account, 'persona_id = ', persona)
                self.persona_id = int(persona)
                new_print(fifa_account, "self.persona_id = ", self.persona_id)
                new_print(fifa_account, 'nucleus_id = ', self.nucleus_id)

                new_print(fifa_account, 'sid = ', self.sid)
                # log_file.write('sid = %s'% str(sid))
                # log_file.write('\n')
                # log_file.closed

                # time.sleep(30)

                self.se_header = {
                    'Content-Type': 'application/json',
                    'Origin': 'https://www.ea.com',
                    'Referer': 'https://www.ea.com/',
                    'User-Agent': user_agent,
                    'X-UT-SID': self.sid,
                    'Accept': '*/*',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'en-US,en;q=0.5',
                    'Connection': 'keep-alive',
                    'Host': fifa_host,
                }
                # 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": %s}''' % sid
                self.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': 'FUT24WEB', 'x-ea-game-id-type': 'easku',
                                          'x-ea-taxv': '1.1'
                                          }
                self.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.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
                                       }

                if self.running_platform != 'console':
                    error = self.check_account_problems(self.fifa_account.id,
                                                        self.web_driver,
                                                        self.nucleus_id,
                                                        self.fifa_account.user_name)
                    if error:
                        fifa_account.login_working = 0
                        fifa_account.save()
                        self.handle_end_bot()
                        return

                self.web_driver.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.sid, last_nucleus=self.nucleus_id,
                        last_persona=self.persona_id)



            except:
                new_print(fifa_account, 'login checker : ', traceback.format_exc())
        fifa_account.login_working = 0
        fifa_account.save()

    def check_account_web_app(self, ):
        time.sleep(2)
        resp = self.se.get(f'{fifa_23_address}/watchlist',
                           headers=self.se_header)
        new_print(self.fifa_account, 'check account_healthy resp = ', resp.text)
        json_resp = resp.json()
        credit = json_resp['credits']
        self.fifa_account.refresh_from_db()
        self.fifa_account.credit = credit
        self.fifa_account.save()
        self.fifa_account.refresh_from_db()

    def check_captcha(self, ):
        elem = wait_for_element('xpath', 'one', "//h2[contains(text(),'Verification Required')]", special='break',
                                driver=self.web_driver)
        if elem:
            new_print(self.fifa_account, 'captcha found')
            return 1
        return 0

    def check_account_problems(self, account_id, driver, nucleus, acc_email):
        error = ''
        elem = wait_for_element('xpath', 'one', "//h2[contains(text(),'Signed Into Another Device')]",
                                special='fast_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='fast_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:
                    traceback.print_exc()

        if error:
            self.trade_worker.error_description = error
            self.trade_worker.has_error = 1
            self.trade_worker.save()
            self.trade_worker.refresh_from_db()

            # cursor2.execute('update accounts set error = 1 , error_desc = %s where id = %s',
            #                 (error, account_id))

            text = error + ' ' + acc_email
            new_print(self.fifa_account, 'error = ', error)
            self.send_message(bot, 'critical', text)
        return error

    def sell_items(self, fifa_account: FifaAccount):
        new_print(fifa_account, 'trade bot : sell items')
        delete_sold_items(self.se, self.se_header, 0)
        items_list = []
        need_sleep = 0
        self.sleep_time = 0
        json_watchlist = get_watchlist(self.fifa_account, self.se, self.options_header, self.se_header).json()
        try:
            watch_items = json_watchlist['auctionInfo']
        except:
            new_print(self.fifa_account, 'watchlist is empty : ', json_watchlist)
            watch_items = []
        for watch_item in watch_items:
            if watch_item['tradeState'] == 'closed' and watch_item['bidState'] == 'highest':
                data = '{"itemData":[{"id":%s,"pile":"trade","tradeId":"%s"}]}' % (watch_item['itemData']['id'],
                                                                                   watch_item['tradeId'])
                new_print(fifa_account, 'item send to trade pile : ', data)
                put_item_for_sale(self.se, self.se_header, data, 0)
                time.sleep(1)
            elif watch_item['tradeState'] == 'closed' and watch_item['bidState'] == 'outbid':
                clear_outbid(self.fifa_account, self.se, self.se_header, watch_item['tradeId'])

        time.sleep(2)
        json_resp = get_trade_pile_2(self.fifa_account, self.se, self.options_header, self.se_header).json()
        try:
            trades = json_resp['auctionInfo']
        except:
            new_print(self.fifa_account, 'trade pile response error : ', json_resp)
            trades = []
        for trade in trades:
            club_id = trade['itemData']['id']
            asset_id = trade['itemData']['assetId']
            resource_id = trade['itemData'].get('resourceId', 0)
            if (not trade['tradeState']) or trade['tradeState'] == 'expired':
                if trade['itemData']['itemType'] != 'player':
                    if trade['tradeState'] == 'expired':
                        new_print(fifa_account, 'quick sell this item')
                        resp2 = self.se.delete(
                            f'{fifa_23_address}/item/%s' % club_id,
                            headers=self.se_header)
                        new_print(fifa_account, resp2.text)
                        # time.sleep(randint(1, 3))
                        time.sleep(1)
                    else:
                        if self.running_platform != 'console':
                            new_print(fifa_account, 'quick sell this item')
                            resp2 = self.se.delete(
                                f'{fifa_23_address}/item/%s' % club_id,
                                headers=self.se_header)
                            new_print(fifa_account, resp2.text)
                            # time.sleep(randint(1, 3))
                            time.sleep(1)
                        else:
                            pass
                else:
                    rating = trade['itemData']['rating']
                    if rating < 75:
                        new_print(fifa_account, 'club id = ', club_id, 'asset id = ', asset_id, 'rating = ',
                                  rating,
                                  'will quick sell')
                        resp2 = self.se.delete(f'{fifa_23_address}/item/%s' % club_id,
                                               headers=self.se_header)
                        new_print(fifa_account, resp2.text)
                        # time.sleep(randint(1, 3))
                        time.sleep(1)
                    else:
                        if self.running_platform != 'console':
                            self.items_sell_get_list(asset_id, club_id, items_list,
                                                     trade['itemData']['rareflag'],
                                                     rating, trade['itemData']['teamid'])
                        # else:
                        #     if trade['tradeState'] == 'expired':
                        #         time.sleep(0.5)
                        #         resp = self.get_price_limit(club_id)
                        #         js_resp = resp.json()
                        #         new_print(fifa_account, 'item price limits = ', js_resp)
                        #         min_price = js_resp[0]['minPrice']
                        #         if trade['startingBid'] == min_price:
                        #             new_print(fifa_account, 'club id = ', club_id, 'asset id = ', asset_id,
                        #                       'rating = ', rating,
                        #                       'will quick sell')
                        #             resp2 = self.se.delete(
                        #                 f'{fifa_23_address}/item/%s' % (
                        #                     club_id,),
                        #                 headers=self.se_header)
                        #             new_print(fifa_account, resp2.text)
                        #             # time.sleep(randint(1, 3))
                        #             time.sleep(1)
                        #         else:
                        #             card_info = self.public_moves.get_player_data_by_asset_id(
                        #                 player_asset_id=asset_id)
                        #             new_print(fifa_account, 'asset id = ', asset_id, 'rate = ', rating)
                        #             new_print(fifa_account, 'card info = ', card_info)
                        #             try:
                        #                 price, update_time = self.get_player_price_from_futbin_web_app(
                        #                     card_info[0],
                        #                     rating,
                        #                     card_info[1],
                        #                     player_club=trade['itemData']['teamid'],
                        #                     player_rare=trade['itemData']['rareflag']
                        #                 )
                        #                 back_steps = int(price)
                        #                 for i in range(7):
                        #                     back_steps = get_previous_price_grade(back_steps)
                        #                 if int(price) != 0 and back_steps <= int(min_price):
                        #                     new_print(fifa_account,
                        #                               'quick sell this item price = %s and min price = %s',
                        #                               (price, min_price))
                        #                     resp2 = self.se.delete(
                        #                         f'{fifa_23_address}/item/%s' % (
                        #                             club_id,),
                        #                         headers=self.main_dic['header'])
                        #                     new_print(fifa_account, resp2.text)
                        #                     time.sleep(1)
                        #                 else:
                        #                     new_print(fifa_account,
                        #                               'will not quick sell this item player price = %s and min price = %s',
                        #                               (price,
                        #                                min_price))
                        #             except:
                        #                 new_print(fifa_account, traceback.format_exc())

                        need_sleep = 1

            # elif trade['tradeState'] == 'expired':
            #
            #     items_sell_get_list(asset_id, club_id, items_list,trade['itemData']['rareflag'])
            #     need_sleep = 1

        json_resp = self.get_items().json()
        try:
            unass_data = json_resp['itemData']
        except:
            new_print(self.fifa_account, 'unass data not found : ', json_resp)
            unass_data = []
        for unass in unass_data:
            asset_id = unass['assetId']
            club_id = unass['id']
            resource_id = unass.get('resourceId', 0)
            # if club_id not in current_sbc_club_items:
            if True:
                if unass['itemType'] == 'misc':
                    data = '{"apply":[]}'
                    resp = self.se.post(
                        f'{fifa_23_address}/item/%s' % club_id,
                        data=data, headers=self.se_header)
                    try:
                        json_resp = resp.json()
                        res_id = json_resp['itemData'][0]['resourceId']
                        resp = self.se.post(
                            f'{fifa_23_address}/playerpicks/item/%s/select' % res_id,
                            headers=self.se_header
                        )
                        json_resp = resp.json()
                        club_id = json_resp['id']
                        data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
                        new_print(fifa_account, 'data =', data)
                        new_print(fifa_account, 'item send to club')
                        put_item_for_sale(self.se, self.se_header, data, 0)
                    except:
                        new_print(fifa_account, traceback.format_exc())
                        new_print(fifa_account, 'no need to send to club')

                # elif unass['untradeable'] or unass['itemType'] == 'contract':
                elif unass['untradeable']:
                    data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
                    new_print(fifa_account, 'data =', data)
                    new_print(fifa_account, 'item send to club')
                    # put_item_for_sale(data)
                    resp = put_item_for_sale(self.se, self.se_header, data, 0)
                    json_resp = resp.json()
                    try:
                        reason = json_resp['itemData'][0]['reason']
                        new_print(fifa_account, 'duplicate item , reason', reason)
                        new_print(fifa_account, 'club id = ', club_id, 'asset id = ', asset_id, 'will quick sell')
                        self.se.delete(f'{fifa_23_address}/item/%s' % club_id,
                                       headers=self.se_header)
                    except:
                        pass
                    time.sleep(1)
                elif unass['itemType'] != 'player':
                    new_print(fifa_account, 'item founded')
                    # if unass['itemType'] == 'contract':
                    #     if (not sbc_worker.first_xi) and (not sbc_worker.puzzle_master) and self.manual_loyal:
                    #         data = '{"itemData":[{"id":%s,"pile":"club"}]}' % \
                    #                (club_id)
                    #         new_print(fifa_account, 'data =', data)
                    #         new_print(fifa_account, 'item send to club')
                    #         # put_item_for_sale(data)
                    #         put_item_for_sale(self.se, self.se_header, data, 0)
                    #     else:
                    #         new_print(fifa_account, 'contract found , club id = ', club_id, 'will quick sell')
                    #         self.se.delete(f'{fifa_23_address}/item/%s' % (
                    #             club_id,), headers=self.se_header)
                    #         time.sleep(1)
                    #
                    #     continue

                    # if self.running_platform == 'console':
                    #     # if self.all_sbc_completed:
                    #     if resource_id in self.useful_items.values():
                    #         new_print(fifa_account, 'useful item found')
                    #         data = '{"itemData":[{"id":%s,"pile":"trade"}]}' % \
                    #                (club_id)
                    #         new_print(fifa_account, 'data =', data)
                    #         new_print(fifa_account, 'item send to transfer list')
                    #         # put_item_for_sale(data)
                    #         put_item_for_sale(self.se, self.se_header, data, 0)
                    #     else:
                    #         new_print(fifa_account, 'quick sell this item')
                    #         self.se.delete(f'{fifa_23_address}/item/%s' % (
                    #             club_id,), headers=self.se_header)

                    # else:
                    #     resp = self.get_price_limit(club_id)
                    #     js_resp = resp.json()
                    #     min_price = js_resp[0]['minPrice']
                    #     max_price = js_resp[0]['maxPrice']
                    #     self.item_put_for_sale(club_id, '', 0, start_price=min_price, buy_now_price=max_price)
                    resp = self.get_price_limit(club_id)
                    js_resp = resp.json()
                    min_price = js_resp[0]['minPrice']
                    max_price = js_resp[0]['maxPrice']
                    self.item_put_for_sale(club_id, '', 0, start_price=min_price, buy_now_price=max_price)
                    # data = '{"itemData":[{"id":%s,"pile":"club"}]}' % \
                    #        (club_id)
                    # print 'need this one for sbc'
                    # print 'data =', data
                    # print 'item send to club'
                    # # put_item_for_sale(data)
                    # resp = put_item_for_sale(data)

                    time.sleep(1)
                else:

                    # if unass['rareflag'] < 2:
                    rating = unass['rating']
                    if rating < 75:
                        new_print(fifa_account, 'low level player founded')

                        if self.running_platform == 'console':
                            # data = '{"itemData":[{"id":%s,"pile":"trade"}]}' % \
                            #        (club_id)
                            # new_print(fifa_account,'data =', data)
                            # new_print(fifa_account,'item send to transfer list')
                            # # put_item_for_sale(data)
                            # self.put_item_for_sale(data)
                            new_print(fifa_account, 'quick sell this item')
                            self.se.delete(f'{fifa_23_address}/item/%s' % (
                                club_id,), headers=self.se_header)
                        else:
                            resp = self.get_price_limit(club_id)
                            js_resp = resp.json()
                            min_price = js_resp[0]['minPrice']
                            max_price = js_resp[0]['maxPrice']
                            self.item_put_for_sale(club_id, '', 0, start_price=min_price,
                                                   buy_now_price=max_price)
                        time.sleep(1)
                        # print 'club id = ',club_id, 'asset id = ', asset_id , 'rating = ',rating, 'will quick sell'
                        # self.se.delete(f'{fifa_23_address}/item/%s' % (
                        #      club_id), headers=self.se_header)
                    else:
                        sell = 1
                        # if not self.manual_loyal:
                        #     if unass['rareflag'] < 2:
                        #         if not self.main_dic['first_xi']:
                        #             sell = self.check_for_use_in_loyal_sbc(asset_id, 1, 20, sell, unass,
                        #                                                    team=unass['teamid'])
                        #         if not self.main_dic['puzzle_master']:
                        #             sell = self.check_for_use_in_loyal_sbc(asset_id, 4, 36, sell, unass,
                        #                                                    team=unass['teamid'])

                        if sell:
                            self.items_sell_get_list(asset_id, club_id, items_list, unass['rareflag'], rating,
                                                     unass['teamid'])
                            need_sleep = 1
                        else:
                            data = '{"itemData":[{"id":%s,"pile":"club"}]}' % \
                                   (club_id)
                            new_print(fifa_account, 'need this one for sbc')
                            new_print(fifa_account, 'data =', data)
                            new_print(fifa_account, 'item send to club')
                            # put_item_for_sale(data)
                            resp = put_item_for_sale(self.se, self.se_header, data, 0)
                            json_resp = resp.json()
                            try:
                                reason = json_resp['itemData'][0]['reason']
                                new_print(fifa_account, 'duplicate item')
                                self.items_sell_get_list(asset_id, club_id, items_list, unass['rareflag'],
                                                         rating,
                                                         unass['teamid'])
                                need_sleep = 1
                            except:
                                pass
                            time.sleep(1)
            else:
                data = '{"itemData":[{"id":%s,"pile":"club"}]}' % \
                       (club_id)
                new_print(fifa_account, 'data =', data)
                new_print(fifa_account, 'item send to club')
                # put_item_for_sale(data)
                resp = put_item_for_sale(self.se, self.main_dic['header'], data, 0)
                time.sleep(2)
                # else:
                #     data = '{"itemData":[{"id":%s,"pile":"trade"}]}' % \
                #            (club_id)
                #     print 'data =', data
                #     print 'item send to trade pile'
                #     put_item_for_sale(data)
        if need_sleep:
            new_print(fifa_account, 'sleep for 330 sec ...')
            # print 'item list = ', items_list
            # time.sleep(30)
            for item in items_list:
                # if self.running_platform == 'console':
                #     time.sleep(0.5)
                #     resp = self.get_price_limit(item[1])
                #     js_resp = resp.json()
                #     min_price = js_resp[0]['minPrice']
                #     new_print(fifa_account, 'item price limits = ', js_resp)
                #
                #     card_info = self.public_moves.get_player_data_by_asset_id(player_asset_id=item[0])
                #     new_print(fifa_account, 'asset id = ', item[0], 'rate = ', item[4])
                #     new_print(fifa_account, 'card info = ', card_info)
                #     try:
                #         price, update_time = self.get_player_price_from_futbin_web_app(
                #             card_info[0],
                #             item[4],
                #             card_info[1],
                #             player_club=item[5],
                #             player_rare=item[3]
                #         )
                #         back_steps = int(price)
                #         for i in range(7):
                #             back_steps = get_previous_price_grade(back_steps)
                #         if int(price) != 0 and back_steps <= int(min_price):
                #             new_print(fifa_account, 'quick sell this item price = %s and min price = %s',
                #                       (price, min_price))
                #             resp2 = self.se.delete(
                #                 f'{fifa_23_address}/item/%s' % (
                #                     item[1]), headers=self.main_dic['header'])
                #             new_print(fifa_account, resp2.text)
                #             time.sleep(1)
                #             continue
                #         else:
                #             new_print(fifa_account,
                #                       'will not quick sell this item player price = %s and min price = %s', (price,
                #                                                                                              min_price))
                #     except:
                #         new_print(fifa_account, traceback.format_exc())
                #     data = '{"itemData":[{"id":%s,"pile":"trade"}]}' % \
                #            (item[1])
                #     new_print(fifa_account, 'data =', data)
                #     new_print(fifa_account, 'item send to transfer list')
                #     # put_item_for_sale(data)
                #     put_item_for_sale(self.se, self.main_dic['header'], data, 0)
                #     time.sleep(1)
                # else:
                #     self.sell_process(item[0], item[1], item[2], item[3], item[4], item[5])
                #     time.sleep(3)
                self.sell_process(item[0], item[1], item[2], item[3], item[4], item[5])
                time.sleep(3)
            self.update_credit()
        new_print(self.fifa_account, 'end of sell items')

    def items_sell_get_list(self, asset_id, club_id, items_list, rare, rate, team_id):
        # resp = search_player(asset_id, 0, '',rare=rare)
        # json_resp = resp.json()
        # tr = json_resp['auctionInfo']
        trade_id_list = ''
        # has_trade = 0
        # if not tr:
        #     data = '{"itemData":[{"id":%s,"pile":"club"}]}' % \
        #            (club_id)
        #     print 'data =', data
        #     print 'item send to club'
        #     put_item_for_sale(data)
        #     text = 'item send to club. asset id = %s username = %s'%(asset_id,username)
        #     send_message(bot, 123, text)
        # else:
        # for t in tr:
        #     if t['expires'] < 300:
        #         has_trade = 1
        #         trade_id_list += ',' + str(t['tradeId'])
        # if has_trade:
        #     trade_id_list = trade_id_list[1:]
        items_list.append([asset_id, club_id, trade_id_list, rare, rate, team_id])

    def get_price_limit(self, player_club_id):
        self.se.options(
            f'{fifa_23_address}/marketdata/item/pricelimits?itemIdList=%s' % (
                player_club_id,),
            headers=self.options_header)
        resp = force_get(
            f'{fifa_23_address}/marketdata/item/pricelimits?itemIdList=%s' % (
                player_club_id,),
            self.fifa_account,
            self.se,
            self.se_header)
        return resp

    def get_items(self, ):
        self.se.options(
            f'{fifa_23_address}/purchased/items',
            headers=self.options_header)
        resp = force_get(
            f'{fifa_23_address}/purchased/items',
            self.fifa_account,
            self.se,
            self.se_header)
        return resp

    def sell_process(self, asset_id, club_id, trade_id_list, rare, rating, team_id):
        trade_id_list = ''
        if trade_id_list:
            options_header = {'Accept': '*/*',
                              'Accept-Encoding': 'gzip, deflate, br',
                              'Accept-Language': 'en-US,en;q=0.5',
                              'Connection': 'keep-alive',
                              'Host': fifa_host,
                              'Access-Control-Request-Headers': 'content-type,x-ut-sid',
                              'Access-Control-Request-Method': 'PUT',
                              'Origin': 'https://www.ea.com',
                              'Referer': 'https://www.ea.com/',
                              'User-Agent': user_agent
                              }
            self.se.options(
                f'{fifa_23_address}/trade/status/lite?tradeIds=%s' % (str(trade_id_list),),
                headers=options_header)
            resp = force_get(
                f'{fifa_23_address}/trade/status/lite?tradeIds=%s' % (str(trade_id_list),),
                self.fifa_account,
                self.se,
                self.se_header)
            json_resp = resp.json()
            trades = json_resp['auctionInfo']
            bid_list = []
            for trade in trades:
                if trade['currentBid'] != 0:
                    bid_list.append(trade['currentBid'])
            try:
                bid_price = most_common(bid_list)
                new_print(self.fifa_account, 'most bid price =', bid_price, 'asset id ', asset_id)
            except:
                new_print(self.fifa_account, 'bid list is empty')
                bid_price = 800
        else:
            bid_price = 800

        time.sleep(1.5)
        limits = self.get_price_limit(club_id)
        limits_json = limits.json()
        max_price = limits_json[0]['maxPrice']
        new_print(self.fifa_account, 'player limit max_price = ', max_price)
        # complete_number = self.sbc_worker.complete_number
        # force_manual = 0
        # if complete_number > 0:
        #     force_manual = 1
        # price = self.search_price(get_next_price_grade(get_next_price_grade(bid_price)), asset_id,
        #                           trade_mode=3, rare=rare,
        #                           limit_max_price=max_price, force_manual=force_manual)
        price = 0
        # if complete_number == 0:
        time.sleep(0.5)
        resp = self.get_price_limit(club_id)
        js_resp = resp.json()
        min_price = js_resp[0]['minPrice']
        new_print(self.fifa_account, 'item price limits = ', js_resp)
        card_info = get_player_data_by_asset_id(player_asset_id=asset_id)
        new_print(self.fifa_account, 'asset id = ', asset_id, 'rate = ', rating, 'card info = ', card_info)
        try:
            price, update_time = self.get_player_price_from_futbin_web_app(
                card_info[0],
                rating,
                card_info[1],
                player_club=team_id,
                player_rare=rare
            )
            price = int(price)
            back_steps = int(price)
            for i in range(5):
                back_steps = get_previous_price_grade(back_steps)
            if (int(price) != 0 and back_steps <= int(min_price)) and int(price) < 30000:
                new_print(self.fifa_account, 'quick sell this item price = %s and min price = %s',
                          (price, min_price))
                resp2 = self.se.delete(
                    f'{fifa_23_address}/item/%s' % (club_id,),
                    headers=self.se_header)
                new_print(self.fifa_account, resp2.text)
                time.sleep(1)
            else:
                new_print(self.fifa_account,
                          'will not quick sell this item player price = %s and min price = %s' %
                          (price, min_price))
        except:
            new_print(self.fifa_account, traceback.format_exc())

        if not price:
            price = self.search_price(price, asset_id,
                                      trade_mode=3, rare=rare,
                                      limit_max_price=max_price, force_manual=0)
        # for i in range(complete_number):
        #     price = get_previous_price_grade(get_previous_price_grade(get_previous_price_grade(get_previous_price_grade(price))))
        # if complete_number > 0:
        # for i in range(complete_number):
        #     price = get_previous_price_grade(price)
        #
        # if price > 50000:
        #     int_price = 0
        #     try:
        #         a = int(price)
        #         int_price = 1
        #     except:
        #         pass
        #
        #     if int_price:
        #         try:
        #             player_name = ''
        #             players_file = open(file_path + '/new_players.json')
        #             players_data = players_file.read()
        #             players_file.close()
        #             players_data = json.loads(players_data)
        #             for player in players_data['LegendsPlayers']:
        #                 if str(player['id']) == str(asset_id):
        #                     if player.get('c'):
        #                         player_name = player['c']
        #                     else:
        #                         player_name = player['f'] + ' ' + player['l']
        #                     break
        #             if not player_name:
        #                 for player in players_data['Players']:
        #                     if str(player['id']) == str(asset_id):
        #                         if player.get('c'):
        #                             player_name = player['c']
        #                         else:
        #                             player_name = player['f'] + ' ' + player['l']
        #                         break
        #
        #         except:
        #             player_name = ''
        #         text = '''Congratulations. Account %s Earned a good player
        #         player_name = %s
        #         player_price = %s
        #         player_asset = %s
        #         player_rare = %s''' % (self.fifa_account.user_name, player_name, price, asset_id, rare)
        #         self.send_message(bot, 123, text)

        new_print(self.fifa_account, 'price = ', price, 'asset id ', asset_id)
        try:
            price = int(price)
            self.item_put_for_sale(club_id, '', 0, start_price=get_previous_price_grade(price),
                                   buy_now_price=price)
        except:
            new_print(self.fifa_account, traceback.format_exc())

    def get_player_price_from_futbin_web_app(self, player_name, player_rate, player_known_as='', player_club=0,
                                             player_rare=0):
        new_print(self.fifa_account, 'player_name : ', player_name, player_rate, player_known_as)
        params = {
            'year': 24,
            'extra': 1,
            'v': 1,
            'term': player_name
        }
        scraper = cloudscraper.create_scraper(browser={
            'browser': 'firefox',
            'platform': 'linux',
            'mobile': False
        })
        result = scraper.get('https://www.futbin.com/search', params=params)
        list_ids = []
        new_print(self.fifa_account, 'futbin search result : ', result.json())
        if isinstance(result.json(), dict) and result.json().get('error'):
            return 0, 'Never'
        for item in result.json():
            if item.get('rating') != str(player_rate):
                continue
            if unidecode.unidecode(item.get('name').lower()) == unidecode.unidecode(
                    player_known_as.lower()) or unidecode.unidecode(
                item.get('full_name').lower()) == unidecode.unidecode(player_known_as.lower()):
                if player_rare > 1 and (str(player_rare) != str(item['rare_type'])):
                    new_print(self.fifa_account, 'doesnt match rare type')
                else:
                    list_ids.append(item.get('id'))
                continue
            found = 1
            for i in unidecode.unidecode(player_name.lower()).split():
                if not (i in unidecode.unidecode(item.get('full_name').lower())):
                    found = 0
            if found:
                if player_rare > 1 and (str(player_rare) != str(item['rare_type'])):
                    new_print(self.fifa_account, 'doesnt match rare type')
                else:
                    list_ids.append(item.get('id'))
                continue
        new_print(self.fifa_account, 'list ids = ', list_ids)
        for id_item in list_ids:
            new_print(self.fifa_account, 'https://www.futbin.com/24/player/{}/a'.format(id_item))
            player_card_result = scraper.get('https://www.futbin.com/24/player/{}/a'.format(id_item))
            if player_card_result.status_code == 404:
                return 0, 0
            soup = BeautifulSoup(player_card_result.text, "html.parser")
            club_elem = soup.find('th', text='Club ID')
            new_print(self.fifa_account, 'this club = ', club_elem.findNext('td').text)
            if club_elem.findNext('td').text == str(player_club):
                new_print(self.fifa_account, 'club is OK', player_club)
                # new_print(self.fifa_account,)('doesnt match club name. ', player_club)
            else:
                new_print(self.fifa_account, 'doesnt match club name. ', player_club)
                continue
            page_info = soup.find(id='page-info')
            player_price_id = page_info['data-player-resource']
            futbin_prices = scraper.get('https://www.futbin.com/24/playerPrices?player={}'.format(player_price_id)
                                        ).json().get(str(player_price_id), {}).get('prices', {}).get('ps', [])
            futbin_all_prices_list = []
            if futbin_prices.get('updated') == 'Never':
                continue
            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"))
            if len(futbin_all_prices_list) == 0:
                futbin_all_prices_list = ["0"]
            new_print(self.fifa_account, futbin_all_prices_list)
            futbin_player_price = max(set(futbin_all_prices_list), key=futbin_all_prices_list.count)
            if futbin_player_price:
                return futbin_player_price.replace(',', '').replace('.', ''), futbin_prices.get('updated')
        return 0, 0
