import os
import traceback

import django
from django.utils import timezone

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'futplus.settings')
django.setup()

from sbc.models import SBCWorker
from sbc.public_methods import new_print
from accounts.web_login_utils import logout_login
from accounts.models import Console, FifaAccount
from futplus.settings import CONSOLE_NAME
from sbc.sbc_solver import SBCSolver


def run_worker(worker_id):
    uncompleted_worker = SBCWorker.objects.filter(id=worker_id).first()
    uncompleted_worker.last_run_time = timezone.localtime()
    uncompleted_worker.must_done = False
    uncompleted_worker.save()
    uncompleted_worker.fifa_account.last_run_time = timezone.localtime()
    uncompleted_worker.fifa_account.save()

    fifa_account = uncompleted_worker.fifa_account
    # if not fifa_account.active:
    if True:
        fifa_account.need_captcha = 0
        fifa_account.active = 1
        fifa_account.can_kill_by_mother = False
        fifa_account.save()
        sbc_solver_item = SBCSolver(uncompleted_worker.id, fifa_account.id, fifa_account.user_name,
                                    fifa_account.password,
                                    fifa_account.platform, uncompleted_worker.manual_loyal)
        try:
            logout_login(sbc_solver_item, uncompleted_worker, fifa_account)
        except Exception as e:
            new_print(fifa_account, 'login in celery task error : ', traceback.print_exc())
            # handle_end_bot()

        fifa_account.refresh_from_db()
        if fifa_account.active:
            sbc_solver_item.sbc_solver_core()
        else:
            uncompleted_worker.has_error = True
            uncompleted_worker.error_description = 'error in login'
            uncompleted_worker.save()


while True:
    console = Console.objects.filter(name=CONSOLE_NAME).first()
    if console:
        this_console_accounts = FifaAccount.objects.filter(console=console).order_by('last_run_time').all()
        for acc in this_console_accounts:
            print('account_email = ', acc.user_name, 'delete_club_number = ', acc.delete_club_number,
                  'delete_club_renewal = ', acc.delete_club_renewal)
        fifa_accounts = FifaAccount.objects.filter(console=console).all()
        must_break = False
        for fifa_account in fifa_accounts:
            existed_sbc_worker = SBCWorker.objects.filter(
                is_done=False, has_error=False,
                running_platform='console',
                fifa_account=fifa_account,
                manual_loyal=True
            ).first()
            if existed_sbc_worker:
                print('existed sbc worker found. worker id =', existed_sbc_worker.id, 'account email = ',
                      fifa_account.user_name)
                run_worker(worker_id=existed_sbc_worker.id)
                must_break = True
                break
        if must_break:
            print('must break')
            break
        last_sbc_worker = SBCWorker.objects.filter()
        fifa_account = FifaAccount.objects.filter(console=console, delete_club_number__lt=5).order_by(
            'last_run_time').first()
        if not fifa_account:
            print('account under 5 delete club not found')
            fifa_account = FifaAccount.objects.filter(
                console=console, delete_club_number__lt=10, delete_club_renewal=True
            ).order_by('last_run_time').first()

        if fifa_account:
            print('account email = ', fifa_account.user_name)
            sbc_worker, created = SBCWorker.objects.get_or_create(
                is_done=False, has_error=False,
                running_platform='console',
                fifa_account=fifa_account,
                manual_loyal=True
            )
            run_worker(worker_id=sbc_worker.id)
        else:
            print('all accounts is done')
            break
    else:
        print('console not found in database')
        break

    # TODO : remove this line
    break
