import io
from datetime import timedelta

from mox3 import mox

import wsgiservice
import wsgiservice.application
import wsgiservice.exceptions
from webob import Request


def test_getapp():
    """get_app returns a list of resources from the dictionary."""
    app = wsgiservice.get_app(globals())
    print(app)
    print(app._resources)
    assert isinstance(app, wsgiservice.application.Application)
    assert len(app._resources) == 7
    resources = (Resource1, Resource2, Resource3, Resource4, Resource5,
        Resource6)
    assert app._resources[0] in resources
    assert app._resources[1] in resources
    assert app._resources[2] in resources
    assert app._resources[3] in resources
    assert app._resources[4] in resources
    assert app._resources[5] in resources


def test_app_handle_404():
    """Application returns a 404 status code if no resource is found."""
    app = wsgiservice.get_app(globals())
    req = Request.blank('/foo', {'HTTP_ACCEPT': 'text/xml'})
    res = app._handle_request(req)
    print(res)
    assert res.status == '404 Not Found'
    assert res.body == b'<response><error>' \
        b'The requested resource does not exist.</error></response>'
    assert res.headers['Content-Type'] == 'text/xml; charset=UTF-8'


def test_app_handle_method_not_allowed():
    """Application returns 405 for known but unimplemented methods."""
    app = wsgiservice.get_app(globals())
    req = Request.blank('/res2', {'REQUEST_METHOD': 'GET'})
    res = app._handle_request(req)
    print(res)
    assert res.status == '405 Method Not Allowed'
    assert res.body == b''
    assert res._headers['Allow'] == 'OPTIONS, POST, PUT'


def test_app_handle_method_not_known():
    """Application returns 501 for unknown and unimplemented methods."""
    app = wsgiservice.get_app(globals())
    req = Request.blank('/res2', {'REQUEST_METHOD': 'PATCH'})
    res = app._handle_request(req)
    print(res)
    assert res.status == '501 Not Implemented'
    assert res.body == b''
    assert res._headers['Allow'] == 'OPTIONS, POST, PUT'


def test_app_handle_response_201_abs():
    """raise_201 used the location header directly if it is absolute."""
    app = wsgiservice.get_app(globals())
    req = Request.blank('/res2', {'REQUEST_METHOD': 'POST'})
    res = app._handle_request(req)
    print(res)
    assert res.status == '201 Created'
    assert res.body == b''
    assert res.location == '/res2/test'


def test_app_handle_response_201_rel():
    """raise_201 adds relative location header to the current request path."""
    app = wsgiservice.get_app(globals())
    req = Request.blank('/res2', {'REQUEST_METHOD': 'PUT'})
    res = app._handle_request(req)
    print(res)
    assert res.status == '201 Created'
    assert res.body == b''
    assert res.location == '/res2/foo'


def test_app_handle_response_201_ext():
    """raise_201 ignores extension in the current path."""
    app = wsgiservice.get_app(globals())
    req = Request.blank('/res2.json', {'REQUEST_METHOD': 'PUT'})
    res = app._handle_request(req)
    print(res)
    assert res.status == '201 Created'
    assert res.body == b''
    assert res.location == '/res2/foo'


def test_app_handle_options():
    """Resource provides a good default for the OPTIONS method."""
    app = wsgiservice.get_app(globals())
    req = Request.blank('/res2', {'REQUEST_METHOD': 'OPTIONS'})
    res = app._handle_request(req)
    print(res)
    assert res.status == '200 OK'
    assert res._headers['Allow'] == 'OPTIONS, POST, PUT'


def test_app_get_simple():
    """Application handles GET request and ignored POST data in that case."""
    app = wsgiservice.get_app(globals())
    body = b'foo=42&baz=foobar'
    req = Request.blank('/res1/theid', {
        'CONTENT_LENGTH': str(len(body)),
        'CONTENT_TYPE': 'application/x-www-form-urlencoded',
        'wsgi.input': io.BytesIO(body)})
    res = app._handle_request(req)
    print(res)
    assert res.status == '200 OK'
    assert res._headers['Content-MD5'] == '8d5a8ef21b4afff94c937faabfdf11fa'
    assert res.body == b"<response>GET was called with id theid, " \
        b"foo None</response>"


def test_app_head_revert_to_get_simple():
    """Application converts a HEAD to a GET request but doesn't send body."""
    app = wsgiservice.get_app(globals())
    body = b'foo=42&baz=foobar'
    req = Request.blank('/res1/theid', {
        'REQUEST_METHOD': 'HEAD',
        'CONTENT_LENGTH': str(len(body)),
        'CONTENT_TYPE': 'application/x-www-form-urlencoded',
        'wsgi.input': io.BytesIO(body)})
    res = app._handle_request(req)
    print(res)
    assert res.status == '200 OK'
    assert res.body == b''


def test_app_post_simple():
    """Application handles normal POST request."""
    app = wsgiservice.get_app(globals())
    body = b'foo=42&baz=foobar'
    req = Request.blank('/res1/theid', {
        'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': str(len(body)),
        'CONTENT_TYPE': 'application/x-www-form-urlencoded',
        'wsgi.input': io.BytesIO(body)})
    res = app._handle_request(req)
    print(res)
    assert res.status == '200 OK'
    assert res.body == b"<response>POST was called with id theid, " \
        b"foo 42</response>"


def test_app_wsgi():
    """Application instance works as a WSGI application."""
    app = wsgiservice.get_app(globals())
    env = Request.blank('/res1/theid.json').environ
    start_response = mox.MockAnything()
    start_response('200 OK', [('Content-Length', '40'),
        ('Content-Type', 'application/json; charset=UTF-8'),
        ('Content-MD5', 'd6fe631718727b542d2ecb70dfd41e4b')])
    mox.Replay(start_response)
    res = app(env, start_response)
    print(res)
    mox.Verify(start_response)
    assert res == [b'"GET was called with id theid, foo None"']


def test_validation_method():
    """Resource validates a method parameter which was set on the method."""
    inst = Resource1(None, None, None)
    inst.validate_param(inst.POST, 'foo', '9')


def test_validation_class():
    """Resource validates a method parameter which was set on the class."""
    inst = Resource1(None, None, None)
    inst.validate_param(inst.GET, 'id', 'anyid')


def test_validation_with_re_none_value():
    """Resource rejects empty values if a validation is defined."""
    inst = Resource1(None, None, None)
    try:
        inst.validate_param(inst.GET, 'id', None)
    except wsgiservice
.exceptions.ValidationExceptio
n as e:
        print(e)
        assert str(e) == 'Value for id must not be empty.'
    else:
        assert False, "Expected an exception!"


def test_validation_with_re_mismatch():
    """Resource rejects invalid values by regular expression."""
    inst = Resource1(None, None, None)
    try:
        inst.validate_param(inst.GET, 'id', 'fo')
    except wsgiservice.exceptions.ValidationException as e:
        print(e)
        assert str(e) == 'id value fo does not validate.'
    else:
        assert False, "Expected an exception!"


def test_validation_with_re_mismatch_toolong():
    """Resource rejects invalid values by regular expression."""
    inst = Resource1(None, None, None)
    try:
        inst.validate_param(inst.GET, 'id', 'fooobarrr')
    except wsgiservice.exceptions.ValidationException as e:
        print(e)
        assert str(e) == 'id value fooobarrr does not validate.'
    else:
        assert False, "Expected an exception!"


def test_with_expires():
    """expires decorator correctly sets the Cache-Control header."""
    app = wsgiservice.get_app(globals())
    req = Request.blank('/res3')
    res = app._handle_request(req)
    print(str(res))
    print(res._headers)
    assert res._headers['Cache-Control'] == 'max-age=86400'


def test_with_expires_vary():
    """expires decorator can set the Vary header."""
    app = wsgiservice.get_app(globals())
    req = Request.blank('/res6/uid')
    res = app._handle_request(req)
    print(str(res))
    print(res._headers)
    assert res._headers['Cache-Control'] == 'max-age=86400'
    vary = res._headers['Vary'].split(', ')
    assert len(vary) == 2
    assert 'Authorization' in vary
    assert 'Accept' in vary


def test_with_expires_calculations():