import pytest

from django.contrib.contenttypes.models import ContentType

from passerelle.base.models import ApiUser, AccessRight
from passerelle.sms import SMSGatewayMixin

from test_manager import login, admin_user

import utils

pytestmark = pytest.mark.django_db

klasses = SMSGatewayMixin.__subclasses__()


def test_clean_numbers():
    assert SMSGatewayMixin.clean_numbers(['+ 33 12'], '33') == ['+3312']
    assert SMSGatewayMixin.clean_numbers(['0 0 33 12'], '33') == ['+3312']
    assert SMSGatewayMixin.clean_numbers(['0 12'], '33') == ['+3312']


def test_clean_numbers_no_prefix():
    assert SMSGatewayMixin.clean_numbers(['+ 33 12'], '33', prefix='') == ['3312']
    assert SMSGatewayMixin.clean_numbers(['0 0 33 12'], '33', prefix='') == ['3312']
    assert SMSGatewayMixin.clean_numbers(['0 12'], '33', prefix='') == ['3312']


@pytest.fixture(params=klasses)
def connector(request, db):
    klass = request.param
    kwargs = getattr(klass, 'TEST_DEFAULTS', {}).get('create_kwargs', {})
    kwargs.update({
        'title': klass.__name__,
        'slug': klass.__name__.lower(),
        'description': klass.__name__,
    })
    c = klass.objects.create(**kwargs)
    api = ApiUser.objects.create(username='apiuser', fullname='Api User', description='api')
    obj_type = ContentType.objects.get_for_model(c)
    # no access check
    AccessRight.objects.create(codename='can_send_messages',
                               apiuser=api,
                               resource_type=obj_type,
                               resource_pk=c.pk)
    return c


def test_connectors(app, connector):
    path = '/%s/%s/send/' % (connector.get_connector_slug(), connector.slug)
    result = app.post_json(path, {})
    assert result.json['err'] == 1
    assert result.json['err_desc'].startswith('Payload error: ')

    payload = {
        'message': 'hello',
        'from': '+33699999999',
        'to': ['+33688888888', '+33677777777'],
    }
    for test_vector in getattr(connector, 'TEST_DEFAULTS', {}).get('test_vectors', []):
        with utils.mock_url(connector.URL, test_vector['response']):
            result = app.post_json(path, payload)
            print result.json
            for key, value in test_vector['result'].iteritems():
                assert key in result.json
                assert result.json[key] == value

def test_manage_views(admin_user, app, connector):
    url = '/%s/%s/' % (connector.get_connector_slug(), connector.slug)
    resp = app.get(url)
    assert 'Endpoints' in resp.body
    assert not 'accessright/add' in resp.body
    app = login(app)
    resp = app.get(url)
    assert 'Endpoints' in resp.body
    assert 'accessright/add' in resp.body
