import datetime
import difflib
import os
import random
import re
import string
import time
import traceback

import cv2
import pyotp
import pytz
from PIL import Image
from django.db import close_old_connections
from django.db.models import Q

from accounts.models import FifaAccount, ConsoleReadingAccounts
from futplus.settings import BASE_DIR, TIME_ZONE
from sbc.public_methods import set_sbc_status, enter_world_xboxs, get_last_email, get_image_position, \
    enter_double_check_code_xbox
from utils.realy_public_methods import new_print, get_db_time


class ConsoleAccountsUtils:

    def __init__(self, public_moves_instance):
        from utils.public_moves import PublicMoves
        self.public_moves: PublicMoves = public_moves_instance
        self.fifa_account = self.public_moves.fifa_account
        self.sbc_worker = self.public_moves.sbc_worker
        self.ps4_buttons = self.public_moves.ps4_buttons

    def delete_accounts(self, delete_keys=True, delete_failed_only=False, try_counter=0):
        new_print(self.fifa_account, 'removing accounts , keys : ', delete_keys,
                  ' , failed only : ', delete_failed_only)
        set_sbc_status(self.sbc_worker, 'removing accounts')
        if try_counter > 3:
            print('too many try')
            new_print(self.fifa_account, 'too many try')
            return 'too many try'
        current_s = self.public_moves.just_find_state()
        if not current_s or (current_s and current_s != 'ps4_main'):
            self.ps4_buttons.ps()
            time.sleep(1)
            self.ps4_buttons.cross()
        for nnn in range(10):
            self.ps4_buttons.up()
            time.sleep(.5)
        for nnn in range(5):
            time.sleep(.5)
            self.ps4_buttons.right()
        self.ps4_buttons.cross(sleep_after=2)
        self.ps4_buttons.down(sleep_after=1)
        self.ps4_buttons.cross(sleep_after=2)
        for mnnt in range(5):
            self.ps4_buttons.down()
            self.ps4_buttons.right()
            time.sleep(.5)
        self.ps4_buttons.cross(sleep_after=5)
        for account_count in range(100):
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(
                    os.path.join(BASE_DIR, f'utils/xbox_public/select_remove_account.png'),
                    'screen_shot_tmp.jpg', threshold=.9
            ):
                print('selecting account for remove')
                new_print(self.fifa_account, 'selecting account for remove')
                img = cv2.imread("screen_shot_tmp.jpg")

                # this position is static based on xboxs and monitor 1920 * 1080
                crop_account_name = img[710:770, 850:1070]
                cv2.imwrite('crop_account_name_tmp.jpg', crop_account_name)
                # team_rate = self.get_screen_text('crop_team_rate.jpg', convert=True)
                account_name = self.public_moves.get_screen_text('crop_account_name_tmp.jpg', config='--psm 10 --oem 3', convert=True)
                if delete_failed_only:
                    if self.public_moves.has_image(
                        os.path.join(BASE_DIR, f'utils/xbox_public/empty_user_icon.png'),
                        'screen_shot_tmp.jpg', threshold=.9
                    ):
                        print('empty account found , removing it')
                        new_print(self.fifa_account, 'empty account found , removing it')
                    else:
                        print(account_name, ' will not removed')
                        new_print(account_name, f'account {account_name} will not removed')
                        self.ps4_buttons.right(sleep_after=2)
                        if account_count > 58:
                            print('no account found')
                            new_print(self.fifa_account, 'no account found')
                            return 'no account found'
                        continue
                else:
                    # if 'start' in str(account_name).lower() or 'key' in str(account_name).lower():
                    removing_account_name = str(account_name).lower().strip()
                    if 'start' in removing_account_name or (
                        removing_account_name.startswith('key') and not delete_keys
                    ) or (
                            ('key' not in removing_account_name or (
                                    'key' in removing_account_name and not delete_keys)) and
                            'xbox' not in removing_account_name and
                            'series' not in removing_account_name and
                            'ball' not in removing_account_name and
                            'soccer' not in removing_account_name and
                            len((m := re.search(r'\d+', removing_account_name)).group() if
                            (m := re.search(r'\d+', removing_account_name)) else '0000000') < 6
                    ):
                        print(removing_account_name, ' will not removed')
                        new_print(self.fifa_account, f'account {removing_account_name} will not removed')
                        self.ps4_buttons.right(sleep_after=2)
                        if account_count > 58:
                            print('no account found')
                            return 'no account found'
                        continue
                    else:
                        print(f'account {removing_account_name} will removed')
                        new_print(self.fifa_account, f'account {removing_account_name} will removed')
                self.ps4_buttons.cross(sleep_after=5)
                self.public_moves.get_screen_shot()
                if self.public_moves.has_image(
                    os.path.join(BASE_DIR, f'utils/xbox_public/confirm_delete_account.png'),
                    'screen_shot_tmp.jpg', threshold=.9
                ):
                    new_print(self.fifa_account,
                              f'account {account_name} find confirm delete, press left and cross cross')
                    self.ps4_buttons.left(sleep_after=3)
                    self.ps4_buttons.cross(sleep_after=5)
                    self.ps4_buttons.cross(sleep_after=5)
            else:
                time.sleep(1)
                delete_result = self.delete_accounts(
                    delete_keys=delete_keys,
                    delete_failed_only=delete_failed_only,
                    try_counter=try_counter+1)
                if delete_result == 'too many try':
                    return delete_result

    def check_accounts_func(self):
        new_print(self.fifa_account, 'check accounts started ...')
        set_sbc_status(self.sbc_worker, 'checking accounts')
        self.ps4_buttons.ps()
        time.sleep(1)
        for i in range(6):
            self.ps4_buttons.right()
            time.sleep(.5)
        self.ps4_buttons.down()
        time.sleep(1)
        self.public_moves.get_screen_shot()
        if not self.public_moves.has_image(
                os.path.join(BASE_DIR, f'utils/xbox_add_account/add_switch_selected.png'),
                'screen_shot_tmp.jpg', threshold=.9
        ):
            new_print(self.fifa_account, 'can not find add or switch')
            return
        self.ps4_buttons.cross()
        time.sleep(5)
        readed_gamertag = []
        server_exists_gamertag = []
        for iie in FifaAccount.objects.filter(
                Q(delete_console_reason=None) | Q(delete_console_reason=''),
                console=self.fifa_account.console):
            if len(iie.name_in_console) < 4:
                server_exists_gamertag.append(f'{iie.name_in_console} {iie.platform.replace("xboxs", "series")}')
            else:
                server_exists_gamertag.append(str(iie.name_in_console))
        new_print(self.fifa_account, 'server exists gamer tag: ', server_exists_gamertag)

        for i in range(100):
            self.ps4_buttons.down()
            time.sleep(2)
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/add_guest.png'),
                    'screen_shot_tmp.jpg'
            ):
                new_print(self.fifa_account, 'check accounts , add guest button found , break.')
                self.ps4_buttons.circle()
                time.sleep(1)
                self.ps4_buttons.circle()
                break
            select_left = self.public_moves.get_image_position(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/select_left.png'),
                'screen_shot_tmp.jpg')
            select_right = self.public_moves.get_image_position(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/select_right.png'),
                'screen_shot_tmp.jpg')
            image = Image.open("screen_shot_tmp.jpg")  # Load image.
            try:
                if (select_left.get('top_left')[0] > select_right.get('bottom_right')[0] or
                        select_left.get('top_left')[1] > select_right.get('bottom_right')[1]):
                    cropped_image = image.crop((1, 1, 2, 2))  # Crop the image.
                else:
                    cropped_image = image.crop(
                        (select_left.get('top_left')[0] + 100, select_left.get('top_left')[1]) +
                        select_right.get('bottom_right'))  # Crop the image.
            except ValueError:
                new_print(self.fifa_account, 'search gamertag error : ', traceback.format_exc())
                continue
            # todo : add resize to read text better
            # cv2.resize()
            cropped_image.save(f'user_name{i}_tmp.png')  # Save the image.
            image = cv2.imread(f'user_name{i}_tmp.png', cv2.IMREAD_GRAYSCALE)
            image = cv2.resize(image, None, fx=5, fy=5, interpolation=cv2.INTER_CUBIC)
            cv2.imwrite(f"user_name_2_{i}_tmp.png", image)
            selected_crop_text = f"{self.public_moves.get_screen_text(f'user_name_2_{i}_tmp.png', config='tessedit_char_whitelist=0123456789abcdefghijklmnopqrstuvwxyz@#_',)}".lower()
            self.public_moves.get_screen_text(f'user_name_2_{i}_tmp.png').lower()
            new_print(self.fifa_account, 'read user name : ', selected_crop_text)
            readed_gamertag.append(selected_crop_text)

        # استخراج تگ از هر خط (اول و دومین کلمه)
        def extract_tag(line: str) -> str:
            parts = line.strip().split()
            if len(parts) >= 2:
                return f"{parts[0]} {parts[1]}"
            return parts[0] if parts else ''

        readed_tags = [extract_tag(line) for line in readed_gamertag]

        # تابع مقایسه با درنظر گرفتن اهمیت کلمه اول
        def is_similar(a: str, b: str, threshold=0.8) -> bool:
            a_parts = a.lower().split()
            b_parts = b.lower().split()

            # اگر هر دو تگ دو بخشی هستن
            if len(a_parts) >= 2 and len(b_parts) >= 2:
                # کلمه دوم (پلتفرم) باید یکی باشه مثل series / xbox360
                if a_parts[1] != b_parts[1]:
                    return False

                # کلمه اول باید تا حدی شبیه باشه (مثلاً rec vs c)
                tag_similarity = difflib.SequenceMatcher(None, a_parts[0], b_parts[0]).ratio()
                if tag_similarity < 0.5:  # مثلاً کمتر از 50٪ شباهت
                    return False

            # مقایسه نهایی کامل رشته
            similarity = difflib.SequenceMatcher(None, a.lower(), b.lower()).ratio()
            return similarity >= threshold

        ConsoleReadingAccounts.objects.filter(console=self.fifa_account.console).delete()

        matched_tags = []
        duplicates = []
        not_in_server = []
        not_in_readed = []

        # پیدا کردن تکراری‌های تقریبی در لیست ربات
        for i in range(len(readed_tags)):
            for j in range(i + 1, len(readed_tags)):
                if is_similar(readed_tags[i], readed_tags[j]):
                    duplicates.append((readed_tags[i], readed_tags[j]))

        # آیتم‌هایی که در ربات هست ولی در سرور نیست (با تطابق تقریبی)
        for tag2 in readed_tags:
            matched = False
            for tag1 in server_exists_gamertag:
                if is_similar(tag2, tag1):
                    matched_tags.append((tag2, tag1))
                    matched = True
                    break
            if not matched:
                not_in_server.append(tag2)

        # آیتم‌هایی که در سرور هست ولی در ربات نیست
        for tag1 in server_exists_gamertag:
            if not any(is_similar(tag1, tag2) for tag2 in readed_tags):
                not_in_readed.append(tag1)

        # خروجی نهایی
        new_print(self.fifa_account, "matched gamer tags")
        for a, b in matched_tags:
            new_print(self.fifa_account, f"  - {a} ≈ {b}")
            ConsoleReadingAccounts.objects.create(
                console=self.fifa_account.console,
                status_code=1,
                description=f"matched gamer tags - {a} ≈ {b}")

        new_print(self.fifa_account, "duplicate gamer tags in reading accounts")
        for a, b in duplicates:
            new_print(self.fifa_account, f"  - {a} ≈ {b}")
            ConsoleReadingAccounts.objects.create(
                console=self.fifa_account.console,
                status_code=4,
                description=f"duplicate gamer tags in reading accounts - {a} ≈ {b}")

        new_print(self.fifa_account, "gamer tags exists in reading accounts but not found in server")
        for d in not_in_server:
            new_print(self.fifa_account, f"  - {d}")
            ConsoleReadingAccounts.objects.create(
                console=self.fifa_account.console,
                status_code=3,
                description=f"gamer tags exists in reading accounts but not found in server - {d}")

        new_print(self.fifa_account, "gamer tags exists in server but not found in reading accounts")
        for d in not_in_readed:
            new_print(self.fifa_account, f"  - {d}")
            ConsoleReadingAccounts.objects.create(
                console=self.fifa_account.console,
                status_code=2,
                description=f"gamer tags exists in server but not found in reading accounts - {d}")

        new_print(self.fifa_account, 'read gamer tag ', readed_gamertag)
        new_print(self.fifa_account, 'server gamer tags ', server_exists_gamertag)


    def link_origin_account(self):
        new_print(self.fifa_account, 'start link with origin')
        try_again = 0
        local_tz = pytz.timezone('Asia/Tehran')
        start_time_4 = datetime.datetime.now(local_tz)
        while True:
            time.sleep(1)
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/need_link_account_step_1.png'),
                    'screen_shot_tmp.jpg'):
                new_print(self.fifa_account, 'link origin account step 1')
                self.ps4_buttons.cross()
                time.sleep(5)
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/need_link_account_step_2.png'),
                    'screen_shot_tmp.jpg'):
                new_print(self.fifa_account, 'link origin account step 2')
                self.ps4_buttons.cross()
                time.sleep(1)
                self.ps4_buttons.cross()
                for nm in range(70):
                    self.ps4_buttons.square()
                    time.sleep(.5)
                enter_world_xboxs(self, self.fifa_account.user_name, has_emoji=True)
                self.ps4_buttons.option()
                time.sleep(1)
                self.ps4_buttons.down()
                time.sleep(1)
                self.ps4_buttons.cross()
                time.sleep(5)
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/need_link_account_step_3.png'),
                    'screen_shot_tmp.jpg'):
                new_print(self.fifa_account, 'link origin account step 3')
                self.ps4_buttons.cross()
                time.sleep(1)
                self.ps4_buttons.cross()
                for nm in range(20):
                    self.ps4_buttons.square()
                    time.sleep(.5)
                enter_world_xboxs(self, self.fifa_account.password)
                self.ps4_buttons.option()
                time.sleep(1)
                self.ps4_buttons.down()
                time.sleep(1)
                self.ps4_buttons.down()
                time.sleep(1)
                self.ps4_buttons.down()
                time.sleep(1)
                self.ps4_buttons.cross()
                time.sleep(5)
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/need_link_account_step_3_1.png'),
                    'screen_shot_tmp.jpg'):
                new_print(self.fifa_account, 'link origin step 3_1 , need verification code')
                set_sbc_status(self.sbc_worker, 'wait for verification code', update_time=True)
                # self.ps4_buttons.down()
                # time.sleep(1)
                # self.ps4_buttons.cross()
                # time.sleep(5)
                # self.ps4_buttons.cross()
                time.sleep(1)
                backup_code = 111111
                backup_object = self.fifa_account.account_backup_code.last()
                try:
                    backup_code = backup_object.backup_code
                    backup_object.backup_code = None
                    backup_object.save(update_fields=['backup_code'])
                    new_print(self.fifa_account, 'backup code is : ', backup_code)
                except:
                    new_print(self.fifa_account, 'cant get back up code , error ', traceback.format_exc())
                if not backup_code:
                    try:
                        db_time = int(get_db_time(timezone_=TIME_ZONE).timestamp())
                        backup_code = pyotp.TOTP(backup_object.app_code).at(db_time)
                        # backup_code = str(pyotp.TOTP(backup_object.app_code).now())
                        new_print(self.fifa_account, 'no back up code found , enter app code , ',
                                  backup_object.app_code, ' totp : ', backup_code)
                    except:
                        new_print(self.fifa_account, 'error on get totp')
                if backup_code:
                    for iiii in range(3):
                        self.ps4_buttons.cross()
                        [self.ps4_buttons.square() for ii in range(16)]
                        time.sleep(5)
                        enter_world_xboxs(self, backup_code, has_emoji=True)
                        time.sleep(5)
                        self.ps4_buttons.option()
                        self.ps4_buttons.down()
                        self.ps4_buttons.down()
                        self.ps4_buttons.down()
                        self.ps4_buttons.cross()
                        time.sleep(5)
                        self.ps4_buttons.cross()
                        time.sleep(5)
                        self.ps4_buttons.cross()
                        time.sleep(5)
                        new_print(self.fifa_account, 'backup code entered')
                        if not self.public_moves.has_image(os.path.join(
                                BASE_DIR,
                                f'utils/{self.fifa_account.platform}_controls/need_link_account_step_3_1.png'),
                                'screen_shot_tmp.jpg'):
                            new_print(self.fifa_account, 'need link not seen again. stop try enter verification')
                            break
                        new_print(self.fifa_account, 'seems verification not entered correct , try again')
                # try:
                #     from sbc.login_to_ea_with_selenium import get_webdriver_without_proxy
                #     web_driver = get_webdriver_without_proxy(email=self.fifa_account.user_name, browser='chrome')
                #     web_driver.get('https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=23&ct=1712835230&rver=7.0.6738.0&wp=MBI_SSL&wreply=https%3a%2f%2foutlook.live.com%2fowa%2f%3fnlp%3d1%26state%3d1%26redirectTo%3daHR0cHM6Ly9vdXRsb29rLmxpdmUuY29tL293YS8%26RpsCsrfState%3d269ea9e9-e1b4-2892-e819-c42b9a998839&id=292841&aadredir=1&CBCXT=out&lw=1&fl=dob%2cflname%2cwld&cobrandid=90015')
                #     time.sleep(5)
                #     name_input = web_driver.find_element(by=By.XPATH, value='//input[@name="loginfmt"]')
                #     name_input.send_keys(self.fifa_account.user_name)
                #     web_driver.find_element(by=By.XPATH, value='//button[@id="idSIButton9"]').click()
                #     time.sleep(10)
                #     password_input = web_driver.find_element(by=By.XPATH, value='//input[@name="passwd"]')
                #     password_input.send_keys(self.fifa_account.xbox_pass)
                #     web_driver.find_element(by=By.XPATH, value='//button[@id="idSIButton9"]').click()
                #     time.sleep(10)
                #     web_driver.find_element(by=By.XPATH, value='//button[@id="declineButton"]').click()
                #     time.sleep(15)
                #     try:
                #         web_driver.find_element(by=By.XPATH, value='//*[@id="threeColumnRollupContainer"]').click()
                #         time.sleep(10)
                #     except:
                #         new_print(self.fifa_account, 'no "other" button found')
                #     try:
                #         security_text = web_driver.find_element(
                #             by=By.XPATH, value='//span[contains(text(), "Your EA Security Code is")]').text
                #         security_code_22 = re.search(r'Your EA Security Code is: (\d+)', security_text).group(1)
                #         new_print(self.fifa_account, 'security message 1 : ', security_text)
                #     except:
                #         security_text = web_driver.find_element(
                #             by=By.XPATH, value='//span[contains(text(), " EA ")]').text
                #         new_print(self.fifa_account, 'security message 2 : ', security_text)
                #         security_code_22 = re.search(r': (\d+)', security_text).group(1)
                #         new_print(self.fifa_account, 'security code 2 : ', security_code_22)
                #     self.focus_on_ps()
                #     time.sleep(5)
                #     self.ps4_buttons.cross()
                #     time.sleep(5)
                #     enter_world_xboxs(self, security_code_22, has_emoji=True)
                #     time.sleep(5)
                #     self.ps4_buttons.option()
                #     self.ps4_buttons.down()
                #     self.ps4_buttons.down()
                #     self.ps4_buttons.down()
                #     self.ps4_buttons.cross()
                #     time.sleep(5)
                #     self.ps4_buttons.cross()
                #     time.sleep(5)
                #     self.ps4_buttons.cross()
                #     time.sleep(5)
                #     web_driver.close()
                #     time.sleep(1)
                #     self.focus_on_ps()
                # except:
                #     new_print(self.fifa_account, 'cant enter security code , error ', traceback.format_exc())
                while True:
                    self.public_moves.get_screen_shot()
                    if self.public_moves.has_image(os.path.join(
                            BASE_DIR, f'utils/{self.fifa_account.platform}_controls/need_link_account_step_3_1.png'),
                            'screen_shot_tmp.jpg'):
                        new_print(self.fifa_account, 'wait until press verification code')
                        self.ps4_buttons.right()
                        self.ps4_buttons.left()
                        time.sleep(60)
                        close_old_connections()
                    else:
                        new_print(self.fifa_account, 'verification entered , break')
                        set_sbc_status(self.sbc_worker, 'verification done', update_time=False)
                        break
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/need_link_account_step_4.png'),
                    'screen_shot_tmp.jpg'):
                new_print(self.fifa_account, 'link origin account step 4')
                self.ps4_buttons.cross()
                time.sleep(5)
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/need_link_account_step_5.png'),
                    'screen_shot_tmp.jpg'):
                self.ps4_buttons.cross()
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/need_link_account_need_reset_pass.png'),
                    'screen_shot_tmp.jpg'):
                new_print(self.fifa_account, 'link origin need reset password')
                set_sbc_status(self.sbc_worker, 'link origin need reset password')
                time.sleep(1000)
                raise Exception('link origin need reset password')
            else:
                new_print(self.fifa_account, 'link account step else , try again : ', try_again)
                if try_again < 2:
                    try_again += 1
                    self.public_moves.errors()
                else:
                    new_print(self.fifa_account, 'link origin account complete')
                    return

    def xboxs_add_new_user(self, email, password, gamer_tag, support_email='', support_password='',
                           support_imap_host='outlook.office365.com'):
        self.ps4_buttons.ps()
        time.sleep(1)
        for i in range(6):
            self.ps4_buttons.right()
            time.sleep(.5)
        self.ps4_buttons.down()
        time.sleep(1)
        self.public_moves.get_screen_shot()
        if not self.public_moves.has_image(
                os.path.join(BASE_DIR, f'utils/xbox_add_account/add_switch_selected.png'),
                'screen_shot_tmp.jpg', threshold=.9
        ):
            print('can not find add or switch')
        self.ps4_buttons.cross()
        time.sleep(1)
        for i in range(100):
            self.ps4_buttons.down()
            time.sleep(.5)
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(
                    os.path.join(BASE_DIR, f'utils/xbox_add_account/add_new_account.png'),
                    'screen_shot_tmp.jpg', threshold=.9
            ):
                self.ps4_buttons.cross()
                break
        # press name
        new_print(self.fifa_account, 'find enter email state.')
        self.public_moves.wait_for_image(
            os.path.join(
                BASE_DIR,
                f'utils/xbox_add_account/sign_in.png'),
            excluded_errors_image=['who_are_u.png', ]
        )
        need_more_space = self.public_moves.wait_for_image(
            os.path.join(
                BASE_DIR,
                f'utils/xbox_add_account/another_person_make_space.png'),
            excluded_errors_image=['who_are_u.png', ],
            wait_time=1,
            check_errors=False,
        )
        if need_more_space:
            new_print(self.fifa_account, 'try to send account mail, ', email)
            return 'need_more_space'
        new_print(self.fifa_account, 'try to send account mail, ', email)
        time.sleep(1)
        enter_world_xboxs(self, email)
        time.sleep(1)
        self.ps4_buttons.option()
        time.sleep(1)
        # press password
        new_print(self.fifa_account, 'try to send account password, ', password)
        self.public_moves.wait_for_image(os.path.join(
            BASE_DIR,
            f'utils/xbox_add_account/enter_your_password.png'),
            excluded_errors_image=['who_are_u.png', ]
        )
        enter_world_xboxs(self, password)
        time.sleep(1)
        self.ps4_buttons.option()
        time.sleep(1)
        #
        after_password_found = self.public_moves.wait_for_images(
            [os.path.join(BASE_DIR, f'utils/xbox_add_account/after_password.png'),
             os.path.join(BASE_DIR, f'utils/xbox_add_account/account_already_added.png'),
             os.path.join(BASE_DIR, f'utils/xbox_add_account/add_mail_help.png'),
             os.path.join(BASE_DIR, f'utils/xbox_public/xbox_account_suspend.png'),
             ],
            excluded_errors_image=['who_are_u.png', ]
        )
        if self.public_moves.has_image(
                os.path.join(BASE_DIR, f'utils/xbox_public/xbox_account_suspend.png'),
                'screen_shot_tmp.jpg', threshold=.9
        ):
            new_print(self.fifa_account, 'account suspend')
            self.ps4_buttons.cross()
            time.sleep(10)
            # raise Exception('account locked')
            return 'suspend'
        if self.public_moves.has_image(
                os.path.join(BASE_DIR, f'utils/xbox_public/account_locked_3.png'),
                'screen_shot_tmp.jpg', threshold=.9
        ) or self.public_moves.has_image(
            os.path.join(BASE_DIR, f'utils/xbox_public/account_locked_4.png'),
                'screen_shot_tmp.jpg', threshold=.9
        ):
            new_print(self.fifa_account, 'account locked')
            self.ps4_buttons.cross()
            time.sleep(10)
            # raise Exception('account locked')
            return 'locked'
        if self.public_moves.has_image(
                os.path.join(BASE_DIR, f'utils/xbox_add_account/account_already_added.png'),
                'screen_shot_tmp.jpg', threshold=.9
        ):
            new_print(self.fifa_account, 'account already created')
            self.ps4_buttons.cross()
            time.sleep(1)
            for i in range(10):
                self.ps4_buttons.circle()
                time.sleep(1)
            return 'exists'
        elif self.public_moves.has_image(
                os.path.join(BASE_DIR, f'utils/xbox_add_account/add_mail_help.png'),
                'screen_shot_tmp.jpg',
        ):
            new_print(self.fifa_account, 'help us protect your account , need add support')
            self.ps4_buttons.right()
            self.ps4_buttons.right()
            self.ps4_buttons.down()
            self.ps4_buttons.cross()
            time.sleep(5)
            # for i in range(100):
            #     self.public_moves.get_screen_shot()
            #     time.sleep(1)
            #     if self.public_moves.has_image(
            #             os.path.join(BASE_DIR, f'utils/xbox_add_account/add_mail_help.png'),
            #             'screen_shot_tmp.jpg',
            #     ):
            #         new_print(self.fifa_account, f'need help in add account {email}')
            #         time.sleep(5)
            #     if i > 98:
            #         raise Exception('Need Help but no one help it')
        counter1 = 0
        local_tz = pytz.timezone('Asia/Tehran')
        start_time = datetime.datetime.now(local_tz)
        last_send_code_time = None
        account_added = False
        creating_status = 'unknown'
        if not after_password_found:
            creating_status = 'after_password_failed'
        try_change_gamer_tag = []
        while counter1 < 10:
            close_old_connections()
            self.fifa_account.refresh_from_db() # this is for keep connection alive
            counter1 += 1
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/double_check.png'),
                    'screen_shot_tmp.jpg',
            ) or self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/double_check_2.png'),
                    'screen_shot_tmp.jpg',
            ) or self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/finish_adding_security_info.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'after password 2_1 found')
                self.ps4_buttons.right()
                last_send_code_time = datetime.datetime.now(local_tz) - datetime.timedelta(seconds=5)
                time.sleep(1)
                self.ps4_buttons.cross()
                # start_time = datetime.datetime.now(local_tz)
                time.sleep(5)
                counter1 = 0
                self.public_moves.get_screen_shot()
                if self.public_moves.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/xbox_add_account/double_check_temperrory_error.png'),
                        'screen_shot_tmp.jpg',
                ):
                    new_print(self.fifa_account, 'double check temperrory error : ', email)
                    print('double check temperrory error : ', email)
                    for ntm in range(2):
                        self.ps4_buttons.ps()
                        time.sleep(1)
                        self.ps4_buttons.cross()
                        time.sleep(2)
                    return 'double check temperrory error'
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/your_other_email.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'whats your other email , enter support email')
                self.ps4_buttons.cross()
                time.sleep(2)
                for iit in range(20):
                    self.ps4_buttons.square()
                enter_world_xboxs(self, support_email)
                last_send_code_time = datetime.datetime.now(local_tz) - datetime.timedelta(seconds=5)
                time.sleep(2)
                self.ps4_buttons.option()
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/enter_double_check_code.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'enter double check code')
                security_code = None
                for wait_time in range(20):
                    last_email = get_last_email(
                        imap_user=support_email, imap_pass=support_password, imap_host=support_imap_host
                    )
                    if last_email.get('body', None) and last_email.get('time') > last_send_code_time:
                        # get security code
                        search_security_code = re.search(r'Security code: (\d+)', last_email.get('body'))
                        if search_security_code:
                            security_code = search_security_code.group(1)
                            break
                    else:
                        print('last email : ', last_email.get('time'), ' start time : ', last_send_code_time)
                        time.sleep(10)
                        continue
                if security_code is None:
                    new_print(self.fifa_account, 'can not get security code : ', email)
                    print('can not get security code', email)
                    for ntm in range(2):
                        self.ps4_buttons.ps()
                        time.sleep(1)
                        self.ps4_buttons.cross()
                        time.sleep(2)
                    return 'can not get security code'
                print('security code : ', security_code)
                # input(f'please enter {security_code} double check code and continue')
                self.ps4_buttons.option()
                time.sleep(5)
                self.ps4_buttons.cross()
                time.sleep(5)
                for iin in range(10):
                    self.ps4_buttons.square()
                    time.sleep(.5)
                enter_double_check_code_xbox(self, str(security_code))
                last_send_code_time = datetime.datetime.now(local_tz)
                time.sleep(5)
                self.ps4_buttons.option()
                time.sleep(2)
                counter1 = 0
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/after_password.png'),
                    'screen_shot_tmp.jpg',
            ):
                self.ps4_buttons.cross()
                time.sleep(1)
                counter1 = 0
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/after_password_2.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'after password 2 found')
                yes_position = get_image_position(os.path.join(
                    BASE_DIR, f'utils/xbox_add_account/yes_im_in.png'),
                    'screen_shot_tmp.jpg')
                new_print(self.fifa_account, 'after password 2 found yes im in position : ', yes_position)
                if 150 < yes_position.get('top_left')[0] < 400:
                    self.ps4_buttons.cross()
                elif 450 < yes_position.get('top_left')[0] < 700:
                    self.ps4_buttons.right()
                    time.sleep(2)
                    self.ps4_buttons.cross()
                elif 750 < yes_position.get('top_left')[0] < 1000:
                    self.ps4_buttons.right()
                    time.sleep(1)
                    self.ps4_buttons.right()
                    time.sleep(2)
                    self.ps4_buttons.cross()
                else:
                    self.ps4_buttons.cross()
                counter1 = 0
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/after_password_3.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'after password 3 found')
                self.ps4_buttons.cross()
                counter1 = 0
                # account_added = True
                # creating_status = 'success'
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/contact_preference.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'after contact preference found')
                self.ps4_buttons.cross()
                counter1 = 0
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/add_gamertage.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'need enter gamer tag found , tried until now : ', try_change_gamer_tag)
                if len(try_change_gamer_tag) >= 2:
                    return 'gamertag_problem'
                # self.ps4_buttons.up()
                # time.sleep(1)
                self.ps4_buttons.cross()
                time.sleep(1)
                for iiii in range(30):
                    self.ps4_buttons.square()
                random_string = random.choice([random.choice(string.ascii_letters) + str(random.randint(0, 9)), str(random.randint(0, 9)) + random.choice(string.ascii_letters)])
                new_gamer_tag = str(gamer_tag) + ' ' + random_string
                enter_world_xboxs(self, new_gamer_tag, initial_upper=True)
                try_change_gamer_tag.append(new_gamer_tag)
                time.sleep(1)
                self.ps4_buttons.option()
                # self.ps4_buttons.down()
                time.sleep(15)
                self.ps4_buttons.cross()
                time.sleep(15)
                self.public_moves.get_screen_shot()
                if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/add_gamertage.png'),
                    'screen_shot_tmp.jpg',
                ):
                    self.ps4_buttons.circle()
                else:
                    counter1 = 0
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/after_password_4.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'after password 4 found')
                self.ps4_buttons.cross()
                counter1 = 0
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/account_settings_found.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'account settings found in other console')
                if gamer_tag and 'start' in gamer_tag:
                    new_print(self.fifa_account,
                              'start account dont need to save from old settings,'
                              ' gamer tag : ', gamer_tag)
                else:
                    self.ps4_buttons.right()
                    time.sleep(.5)
                self.ps4_buttons.cross()
                time.sleep(.5)
                counter1 = 0
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/signin_security_perference.png'),
                    'screen_shot_tmp.jpg',
            ) or self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/xbox_add_account/no_bariers_menu.png'),
                'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'in security preference')
                for i in range(5):
                    self.ps4_buttons.left()
                    time.sleep(1)
                self.ps4_buttons.cross()
                counter1 = 0
                account_added = True
                creating_status = 'success'
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/xbox_add_account/choose_background_color.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'choosing background color')
                self.ps4_buttons.up()
                time.sleep(.5)
                self.ps4_buttons.cross()
                time.sleep(.5)
                self.ps4_buttons.cross()
                counter1 = 0
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR, f'utils/xbox_add_account/link_controller.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'link controller')
                self.ps4_buttons.right()
                time.sleep(.5)
                self.ps4_buttons.cross()
                counter1 = 0
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR, f'utils/xbox_add_account/make_this_home.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'make this home')
                self.ps4_buttons.right()
                time.sleep(1)
                self.ps4_buttons.cross()
                counter1 = 0
                account_added = True
                creating_status = 'success'
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR, f'utils/xbox_add_account/after_password_5.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'after password 5')
                self.ps4_buttons.cross()
                counter1 = 0
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR, f'utils/xbox_add_account/account_compelete_error.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'account complete error message.finish')
                self.ps4_buttons.cross()
                time.sleep(5)
                for i in range(10):
                    self.ps4_buttons.circle()
                    time.sleep(1)
                time.sleep(1)
                break
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR, f'utils/xbox_add_account/keep_in_touch.png'),
                    'screen_shot_tmp.jpg',
            ):
                new_print(self.fifa_account, 'lets keep in touch')
                self.ps4_buttons.down()
                time.sleep(1)
                self.ps4_buttons.left()
                time.sleep(1)
                self.ps4_buttons.cross()
                time.sleep(5)
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR, f'utils/xbox_add_account/too_many_account_added.png'),
                    'screen_shot_tmp.jpg',
                ):
                new_print(self.fifa_account, 'too many account added , need reset console')
                self.public_moves.console_login_utils.restart_console()
                self.public_moves.console_login_utils.xboxs_go_to_app()
                return self.xboxs_add_new_user(
                    email, password, gamer_tag,
                    support_email=support_email, support_password=support_password, support_imap_host=support_imap_host)
                # self.ps4_buttons.ps()
                # time.sleep(2)
                # self.ps4_buttons.cross()
                # time.sleep(5)
                # raise Exception('Need Gamer Tag')
            if counter1 == 5 and account_added is True:
                self.ps4_buttons.ps()
                time.sleep(5)
                for i in range(10):
                    self.ps4_buttons.circle()
                    time.sleep(1)
                time.sleep(1)
                if self.public_moves.just_find_state():
                    new_print(self.fifa_account, 'account creation success in here 2')
                    creating_status = 'success'
                    break
            time.sleep(10)
            new_print(self.fifa_account, 'add account waiting ...')
        new_print(self.fifa_account, 'Account creation successful')
        return creating_status