import os
import threading
import time
import traceback

import django
from django.utils import timezone



os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'futplus.settings')
django.setup()

from accounts.web_login_utils import logout_login
from sbc.models import SBCWorker
from accounts.models import CloseWebAppTransfers, MuleAccounts
from sbc.sbc_solver import SBCSolver


def run_worker_inject(worker_id, transfer: CloseWebAppTransfers):
    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.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)
        if not fifa_account.proxy:
            try:
                logout_login(sbc_solver_item, uncompleted_worker, fifa_account, )
            except Exception as e:
                traceback.print_exc()
                # handle_end_bot()
        fifa_account.refresh_from_db()
        print('fifa_account.active', fifa_account.active)
        if not fifa_account.active:
            transfer.web_app_is_on_it = False
            transfer.save()
            MuleAccounts.objects.filter(fifa_account=fifa_account).update(in_use=False)
            return False
        # sbc_solver_item.sbc_solver_core()
        sbc_solver_item.web_app_inject_staff(transfer=transfer)


def run_worker_discharge(worker_id, transfer: CloseWebAppTransfers):
    print('worker_id = ', 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.save()
        print('fifa_account_id = ', fifa_account.id)
        sbc_solver_item = SBCSolver(uncompleted_worker.id, fifa_account.id, fifa_account.user_name,
                                    fifa_account.password,
                                    fifa_account.platform, uncompleted_worker.manual_loyal)
        print('fifa_account.proxy = ', fifa_account.proxy)
        if not fifa_account.proxy:
            try:
                print('need to login to account')
                logout_login(sbc_solver_item, uncompleted_worker, fifa_account, )
            except Exception as e:
                traceback.print_exc()
                # handle_end_bot()
        fifa_account.refresh_from_db()
        print('fifa_account.active', fifa_account.active)
        if not fifa_account.active:
            transfer.web_app_is_on_it = False
            transfer.save()
            MuleAccounts.objects.filter(fifa_account=fifa_account).update(in_use=False)
            return False
        # sbc_solver_item.sbc_solver_core()
        sbc_solver_item.web_app_discharge_mode3_staff(transfer=transfer)


for i in range(27):

    transfer = CloseWebAppTransfers.objects.filter(error=False, for_inject=True, first_side_done=True,
                                                   second_side_done=False, web_app_is_on_it=False).first()
    if transfer:
        accounts = MuleAccounts.objects.filter(fifa_account__credit__gt=transfer.buy_now_price, in_use=False,
                                               error=False).order_by(
            'last_used').all()
        for account in accounts:
            discharge_exist = CloseWebAppTransfers.objects.filter(error=False, for_discharge=True,
                                                                  first_side_done=False,
                                                                  first_account=account.fifa_account).first()
            if discharge_exist:
                continue
            sbc_worker, created = SBCWorker.objects.get_or_create(
                fifa_account=account.fifa_account, running_platform='inject')
            sbc_worker.first_xi = True
            sbc_worker.puzzle_master = True
            sbc_worker.manual_loyal = True
            sbc_worker.save()
            if sbc_worker.has_error:
                account.error = True
                account.error_description = sbc_worker.error_description
                account.save()
            else:
                transfer.web_app_is_on_it = True
                transfer.web_app_start_time = timezone.localtime()
                transfer.save()
                print('account = ', account.fifa_account.user_name, 'will buy ', transfer.buy_now_price)
                account.last_used = timezone.localtime()
                account.in_use = True
                account.save()
                threading.Thread(target=run_worker_inject,
                                 kwargs={'worker_id': sbc_worker.id, 'transfer': transfer}).start()
                break

    transfer = CloseWebAppTransfers.objects.filter(error=False, for_discharge=True, first_side_done=False,
                                                   web_app_is_on_it=False).first()
    if transfer:
        try:
            mule_account = MuleAccounts.objects.get(fifa_account=transfer.first_account)
        except:
            transfer.error = True
            transfer.save()
            continue
        sbc_worker, created = SBCWorker.objects.get_or_create(
            fifa_account=transfer.first_account, running_platform='inject')
        sbc_worker.first_xi = True
        sbc_worker.puzzle_master = True
        sbc_worker.manual_loyal = True
        sbc_worker.save()
        if sbc_worker.has_error:
            mule_account.error = True
            mule_account.error_description = sbc_worker.error_description
            mule_account.save()
        else:
            transfer.web_app_is_on_it = True
            transfer.web_app_start_time = timezone.localtime()
            transfer.save()
            print('account = ', mule_account.fifa_account.user_name, 'will buy ', transfer.start_price)
            mule_account.last_used = timezone.localtime()
            mule_account.in_use = True
            mule_account.save()
            th = threading.Thread(target=run_worker_discharge,
                                  kwargs={'worker_id': sbc_worker.id, 'transfer': transfer})
            th.daemon = True
            th.start()

    time.sleep(2)

time.sleep(200)
