import logging
import urllib.request


def check_and_register_sns(request, message):
    """
    Checks if an inbound message is an SNS confirm registration message, and then completes the registration
    :return:
    """
    if message.get('Type', 'None') not in ['SubscriptionConfirmation']:
        ''' Not a subscription request message '''
        return False

    confirmation_url = message.get('SubscribeURL')
    contents = urllib.request.urlopen(confirmation_url).read()
    return True


def check_target_for_common_update(message, model_ref):
    """ A common interface to receive targeted updates on request or update local record on non-targeted """
    from messaging.models import Message
    target = message.get('target', None)
    payload = message['payload']
    if isinstance(payload, dict):  # normalise to list of dicts if single item
        payload = [payload]

    if target is not None:
        if Message.objects.filter(message_id=target).exists() is False:
            ''' Targeted message not for us, so don't handle '''
            return ""

    for item in payload:
        if 'clients' in item:  # this relationship not required here. TODO perhaps use a serializer validation here
            drop = item.pop('clients')
        ''' remove data from item that does not exist in local serializer '''
        unhandled = list(set(item) - set(model_ref.__dict__.keys()))
        for _key in unhandled:
            drop = item.pop(_key)
        obj, created = model_ref.objects.update_or_create(id=item['id'], defaults=item)
        logging.warning(f"{obj}, {created}")
