import json
import urlparse

import mock
import httmock

from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse

from passerelle.base.models import ApiUser, AccessRight


def generic_endpoint_url(connector, endpoint, slug='test'):
    return reverse('generic-endpoint', kwargs={
        'connector': connector, 'slug': slug, 'endpoint': endpoint})


def setup_access_rights(obj):
    api = ApiUser.objects.create(username='all',
                                 keytype='', key='')
    obj_type = ContentType.objects.get_for_model(obj)
    AccessRight.objects.create(codename='can_access', apiuser=api,
                               resource_type=obj_type, resource_pk=obj.pk)
    return obj


class FakedResponse(mock.Mock):

    def json(self):
        return json.loads(self.content)


def mock_url(url, response):
    parsed = urlparse.urlparse(url)
    if not isinstance(response ,str):
        response = json.dumps(response)

    @httmock.urlmatch(netloc=parsed.netloc, path=parsed.path)
    def mocked(url, request):
        return response
    return httmock.HTTMock(mocked)
