from datetime import date

from staff.oebs.controllers.converters import yes_no


def update_intranet_status(rollupper, object_id):
    model_qs = (
        rollupper.model.objects
        .filter(**{rollupper.link_field_name + '__isnull': False})
        .select_related(rollupper.link_field_name)
    )
    if object_id:
        model_qs = model_qs.filter(**{rollupper.key_field_name: object_id})
    for oebs_obj in model_qs:
        oebs_intranet_status = int(yes_no(oebs_obj.staff_usage))
        dis_obj = getattr(oebs_obj, rollupper.link_field_name)
        if dis_obj.intranet_status != oebs_intranet_status:
            dis_obj.intranet_status = oebs_intranet_status
            dis_obj.save()


def map_end_date_to_intranet_status(end_date: date or None) -> int:
    if not end_date:
        return 1

    return 0 if end_date < date.today() else 1
