import re

from django.utils import timezone

from api.utils import get_object
from users.models import SchoolClass


def set_hidden_for(block, visibility_list):
    for v in visibility_list:
        school_class = get_object(SchoolClass, v.school_class_id)
        if v.hidden:
            block.hidden_for.add(school_class)
        else:
            block.hidden_for.remove(school_class)


def set_visible_for(block, visibility_list):
    for v in visibility_list:
        school_class = get_object(SchoolClass, v.school_class_id)
        if v.hidden:
            block.visible_for.remove(school_class)
        else:
            block.visible_for.add(school_class)


def is_private_api_call_allowed(user, body):
    # logged in users should only be able to access all resources if they have a valid license
    # logged in users without valid license have only access to logout, me & coupon mutations

    if user.is_anonymous:
        return False

    if user.is_superuser:
        return True

    body_unicode = body.decode('utf-8')

    if is_endpoint_allowed(body_unicode):
        return True

    license_expiry = user.license_expiry_date

    # all other resources are denied if the license is not valid
    if license_expiry is None:
        return False

    return True


# logout, betalogin, me and coupon resources are always allowed. Even if the user has no valid license
def is_endpoint_allowed(body):
    return re.search(r"mutation\s*.*\s*logout\s*{", body) or re.search(r"query\s*.*\s*me\s*{", body) \
           or re.search(r"mutation\s*Coupon", body) or re.search(r"mutation\s*BetaLogin", body)


def sync_hidden_for(model, school_class_template, school_class_to_sync):
    if model.hidden_for.filter(id=school_class_template.id).exists() and not model.hidden_for.filter(
        id=school_class_to_sync.id).exists():
        model.hidden_for.add(school_class_to_sync)

    if model.hidden_for.filter(id=school_class_to_sync.id).exists() and not model.hidden_for.filter(
        id=school_class_template.id).exists():
        model.hidden_for.remove(school_class_to_sync)


def sync_visible_for(model, school_class_template, school_class_to_sync):
    if model.visible_for.filter(id=school_class_template.id).exists() and not model.visible_for.filter(
        id=school_class_to_sync.id).exists():
        model.visible_for.add(school_class_to_sync)

    if model.visible_for.filter(id=school_class_template.id).exists() and not model.visible_for.filter(
        id=school_class_to_sync.id).exists():
        model.visible_for.add(school_class_to_sync)
