})


def token_removed(sender, instance=None, **kwargs):
    token_logger.info(Token(instance, action="revoked"))


def log_grant_removed(sender, instance=None, **kwargs):
    token_logger.info(DataAccessGrantSerializer(instance, action="revoked"))


def fetching_data(sender, request=None, **kwargs):
    fhir_logger.info(FHIRRequest(request))


def fetched_data(sender, request=None, response=None, **kwargs):
    fhir_logger.info(FHIRResponse(response))


def sls_hook(sender, response=None, **kwargs):
    sls_logger.info(SLSResponse(response))


app_authorized.connect(handle_token_created)
beneficiary_authorized_application.connect(handle_app_authorized)
post_delete.connect(token_removed, sender='oauth2_provider.AccessToken')
post_delete.connect(log_grant_removed, sender='authorization.DataAccessGrant')
pre_fetch.connect(fetching_data)
post_fetch.connect(fetched_data)
post_sls.connect(sls_hook)
from oauth2_provider.signals import app_authorized

from open_auth.utils import send_authorisation_notification


def handle_app_authorized(sender, request, token, **kwargs):
    person = token.user.person
    if person is None:
        pass
    else:
        send_authorisation_notification(token.application.name, person.id)


app_authorized.connect(handle_app_authorized)
AccessToken = get_access_token_model()


def app_authorized_record_grant(sender, request, token, application=None, **kwargs):
    bene = request.user
    if token is not None:
        bene = token.user
        application = token.application

    DataAccessGrant.objects.get_or_create(
        beneficiary=bene,
        application=application,
    )


app_authorized.connect(app_authorized_record_grant)


def revoke_associated_tokens(sender, instance=None, **kwargs):
    tokens = AccessToken.objects.filter(application=instance.application, user=instance.user).all()
    for token in tokens:
        token.revoke()


def archive_removed_grant(sender, instance=None, **kwargs):
    ArchivedDataAccessGrant.objects.create(
        created_at=instance.created_at,
        application=instance.application,
        beneficiary=instance.beneficiary)