from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta, datetime

from django.contrib.auth import get_user_model
from django.core.management import BaseCommand


class Command(BaseCommand):
    def handle(self, *args, **options):
        self.stdout.write("Caution:")
        self.stdout.write("Do you really want to reset **ALL** passwords")
        self.stdout.write("If so, type \"YES\"")

        result = input()
        user_model = get_user_model()

        if result == 'YES':
            users = user_model.objects.all().order_by('email')

            with ThreadPoolExecutor(max_workers=5) as executor:
                executor.map(process_user, users)


def process_user(usr):
    # replace domain with id.skillbox.ch,to ensure unique emails
    usr.email = usr.email.split('@')[0] + f'@skillbox.ch'
    user_model = get_user_model()

    if user_model.objects.filter(email=usr.email).exists():
        usr.email = usr.email.split('@')[0] + f'@{usr.id}.skillbox.ch'

    usr.username = usr.email
    print(usr.email)

    # make license valid for 1 year
    now = datetime.now()

    if usr.license_expiry_date:
        usr.license_expiry_date = now + timedelta(days=365)

    # set password to test
    usr.set_password('test')
    usr.save()
