from core.logger import get_logger
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"

logger = get_logger(__name__)


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):
            logger.info("email not verified")
            return user, EMAIL_NOT_VERIFIED
    except HepClientException:
        return user, UNKNOWN_ERROR

    license = License.objects.get_active_license_for_user(user)

    if not license:
        logger.info("license not found, trying to create")
        license, error_msg = check_and_create_licenses(hep_client, user, token)

        if error_msg:
            logger.warning(error_msg)
            return user, error_msg

        logger.info("creating role")
        create_role_for_user(user, license.for_role.key)

    if license and not license.is_valid():
        logger.info("license is not valid")
        return user, NO_VALID_LICENSE

    return user, None


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

    if product:
        logger.info("product found, creating license")
        license = License.objects.create_license_for_role(
            user,
            product["activated"],
            product["raw"],
            product["license"]["edition"],
            product["order_id"],
            product["isbn"],
        )
    else:
        logger.info("no product found")
        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)
