import random

from django.core.management.base import BaseCommand

from staff.lib.db import atomic
from staff.preprofile.models import Preprofile, PREPROFILE_STATUS
from staff.preprofile.tasks import AutoAdoptPreprofiles


class Command(BaseCommand):
    args = 'preprofile_id'
    help = 'Adopt robots'

    def handle(self, *args, **options):
        with atomic():
            preprofile_id = args[0]
            preprofile = Preprofile.objects.get(id=preprofile_id)

            if preprofile.status != PREPROFILE_STATUS.APPROVED:
                self.stdout.write('Robot {} not approved'.format(preprofile_id))
                return

            preprofile.uid = '{}'.format(random.randint(1, 2000000000))
            preprofile.guid = '{}'.format(random.randint(1, 2000000000))

            preprofile.status = PREPROFILE_STATUS.READY
            preprofile.save()

            AutoAdoptPreprofiles()
