from oauth.hep_client import HepClient, HepClientException
from users.models import License
from users.models import User, UserRole, Role, SchoolClass


EMAIL_NOT_VERIFIED = 'email_not_verified'
UNKNOWN_ERROR = 'unknown_error'
NO_VALID_LICENSE = 'no_valid_license'


def handle_user_and_verify_products(user_data, token):
    hep_client = HepClient()

    user = User.objects.get_or_create_hep_user(user_data)

    try:
        if not hep_client.is_email_verified(user_data):
            return user, EMAIL_NOT_VERIFIED
    except HepClientException:
        return user, UNKNOWN_ERROR

    license = License.objects.get_active_license_for_user(user)

    if not license:
        license, error_msg = check_and_create_licenses(hep_client, user, token)

        if error_msg:
            return user, error_msg

        create_role_for_user(user, license.for_role.key)

    if not license.is_valid():
        return user, NO_VALID_LICENSE

    return user, None


def check_and_create_licenses(hep_client, user, token):
    try:
        product = hep_client.active_myskillbox_product_for_customer(token_dict=token)
    except HepClientException:
        return None, UNKNOWN_ERROR

    if product:
        license = License.objects.create_license_for_role(user, product['activated'], product['raw'],
                                                          product['license']['edition'],
                                                          product['order_id'], product['isbn'])
    else:
        return None, NO_VALID_LICENSE

    return license, None


def create_role_for_user(user, role_key):
    UserRole.objects.get_or_create_role_for_user(user, role_key)

    if role_key == Role.objects.STUDENT_KEY:
        return

    if SchoolClass.objects.filter(users__in=[user]).count() == 0:
        SchoolClass.create_default_group_for_teacher(user)

