import os
import shutil

from django.conf import settings
from django.core.management import BaseCommand

from core.hep_client import HepClient
from core.models import AdminData
from users.models import User, License


class Command(BaseCommand):

    def handle(self, *args, **options):
        "Update licenses via cronjob"

        hep_client = HepClient()

        admin_token = AdminData.objects.get_admin_token()
        hep_users = User.objects.filter(hep_id__isnull=False)

        for hep_user in hep_users:
            product = hep_client.myskillbox_product_for_customer(admin_token, hep_user.hep_id)

            if product and License.objects.filter(licensee=hep_user, order_id=product['order_id']).count() == 0:
                license = License.objects.create_license_for_role(hep_user, product['activated'], product['raw'],
                                                                  product['license']['edition'], product['order_id'],
                                                                  product['isbn'])

                if license.is_valid():
                    hep_user.license_expiry_date = license.expire_date
                    hep_user.save()
