import os
import time
import traceback

import django
import openpyxl
import pyotp

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'futplus.settings')
django.setup()

from sbc.login_to_ea_with_selenium import get_webdriver_with_proxy
from accounts.models import FifaAccount, FifaAccountBackupCode

if __name__ == '__main__':
    def unlink_bot(fifa_account):
        if fifa_account.proxy:
            proxy_ip = fifa_account.proxy.ip_address
            proxy_port = fifa_account.proxy.port
            proxy_user = fifa_account.proxy.user_name
            proxy_pass = fifa_account.proxy.password
            web_driver = get_webdriver_with_proxy(fifa_account.user_name, proxy_ip, proxy_port, proxy_user, proxy_pass)
        else:
            raise Exception('Account Have No Proxy')
        web_driver.get('https://myaccount.ea.com/cp-ui/security/index')
        time.sleep(1)
        email_input = web_driver.find_element_by_xpath('//*[@id="email"]')
        for char in fifa_account.user_name:
            email_input.send_keys(char)
            time.sleep(.1)
        password_input = web_driver.find_element_by_xpath('//*[@id="password"]')
        for char in fifa_account.password:
            password_input.send_keys(char)
            time.sleep(.1)
        web_driver.find_element_by_xpath('//*[@id="logInBtn"]').click()
        time.sleep(10)
        try:
            web_driver.find_element_by_xpath('//*[@id="banned_user_title"]')
            raise Exception('Account is Banned')
        except:
            pass
        try:
            web_driver.find_element_by_xpath('//*[@id="APPLabel"]')
            raise Exception('Account Already has Authenticator')

        except:
            pass
        web_driver.find_element_by_xpath('//*[*[@id="APP"]]/label').click()
        time.sleep(1)
        # web_driver.find_element_by_xpath('//*[*[@id="_eventId"]]').click()
        web_driver.find_element_by_xpath('//a[text()="Send Code"]').click()
        time.sleep(10)

        backup_code = FifaAccountBackupCode.objects.filter(fifa_account=fifa_account).last()
        if backup_code and backup_code.app_code:
            totp_code = pyotp.TOTP(backup_code.app_code).now()
        else:
            raise Exception('No Backup Code Found')
        secret_key_input = web_driver.find_element_by_xpath('//*[@id="twoFactorCode"]')
        for char_2 in totp_code:
            secret_key_input.send_keys(char_2)
            time.sleep(.2)
        web_driver.find_element_by_xpath('//*[*[@id="_eventId"]]').click()
        time.sleep(10)

        web_driver.get('https://myaccount.ea.com/cp-ui/connectaccounts/index')
        time.sleep(10)
        try:
            web_driver.find_element_by_xpath('//a[span[text()="Unlink"]]').click()
        except:
            raise Exception('Unlink button not found')
        time.sleep(5)
        web_driver.find_element_by_xpath('//*[@id="mfa_app_radio_label"]').click()
        time.sleep(1)
        web_driver.find_element_by_xpath('//a[span[span[@id="mfa_send_mfa_code_span"]]]').click()
        time.sleep(10)
        # enter verification code
        secret_key_input2 = web_driver.find_element_by_xpath('//*[@id="mfa_code_input"]')
        totp_code = pyotp.TOTP(backup_code.app_code).now()
        for char_2 in totp_code:
            secret_key_input2.send_keys(char_2)
            time.sleep(.2)
        time.sleep(2)
        web_driver.find_element_by_xpath('//*[@id="submitbtn_mfa_verify_code"]').click()
        time.sleep(10)
        # confirm ea roles
        web_driver.find_element_by_xpath('//*[@id="confirm_unlink_checkbox_label"]').click()
        time.sleep(1)
        web_driver.find_element_by_xpath('//*[@id="confirm-delete"]').click()
        time.sleep(2)
        web_driver.close()
        return 'success'


    def unlink_with_xlsx():
        log_workbook = openpyxl.Workbook()
        log_worksheet = log_workbook.active
        log_worksheet.append(['account', 'status', 'description'])
        print('start unlink account ... ')
        excel_file = openpyxl.load_workbook("xbox_accounts.xlsx")
        sheet = excel_file.active
        rows = list(sheet.iter_rows(values_only=True))
        for row_item in rows[1:]:
            account = FifaAccount.objects.filter(user_name=row_item[0]).first()
            if account:
                try:
                    unlink_bot(fifa_account=account)
                    log_worksheet.append([
                        str(account.user_name),
                        'success',
                        '',
                    ])
                except Exception as error:
                    print(traceback.format_exc())
                    print(error)
                    time.sleep(30000)
                    log_worksheet.append([
                        str(account.user_name),
                        'error',
                        str(error),
                        str(traceback.format_exc())
                    ])
                log_workbook.save('log_unlink_account.xlsx')
            else:
                print(f'Account with name {account} not found')
    unlink_with_xlsx()