from functools import wraps


def validate_sns_message_signature(func):
    """
    This decorator is used to validate NSN message authenticity, auto-confirm SNS subscriptions and unsubscribes to the
    endpoint as well as convert message bodies to json.
    if applicable
    """
    @wraps(func)
    def inner(self, request, params, *args, **kwargs):
        import json
        from sns_message_validator import (
            InvalidCertURLException,
            InvalidSignatureVersionException,
            SignatureVerificationFailureException,
            SNSMessageValidator,
        )
        from rest_framework import exceptions
        if params is None:
            params = self.nor
        sns_message_validator = SNSMessageValidator()
        try:
            sns_message_validator.validate_message(message=params)
        except InvalidCertURLException:
            raise exceptions.ValidationError('Invalid certificate URL.')
        except InvalidSignatureVersionException:
            raise exceptions.ValidationError('Unexpected signature version.')
        except SignatureVerificationFailureException:
            raise exceptions.ValidationError('Failed to verify signature.')

        ''' Confirm subscribe on initial request'''
        if params.get('Type', 'None') in ['SubscriptionConfirmation']:
            import urllib.request
            confirmation_url = params.get('SubscribeURL')
            contents = urllib.request.urlopen(confirmation_url).read()

        ''' Confirm Unsubscribe on request'''
        if params.get('Type', 'None') in ['UnsubscribeConfirmation']:
            import urllib.request
            confirmation_url = params.get('UnsubscribeURL')
            contents = urllib.request.urlopen(confirmation_url).read()

        ''' Attempt parse of message into dict else original string '''
        try:
            json_message = json.loads(params['Message'])
        except Exception as e:
            pass
        else:
            params['Message'] = json_message
        ''' Not a subscription request message '''
        return func(self, request, params, *args, **kwargs)
    return inner


def determine_staff(func):
    """
    Checks the presence of a "token" request parameter and tries to
    authenticate the user based on its content.
    """
    @wraps(func)
    def inner(self, request, *args, **kwargs):

        return func(self, request, *args, **kwargs)
    return inner