import falcon
import pytest
from keri.app import habbing
from keri.vdr import credentialing
from mockito import mock, unstub, when

from dws.core import didding
from dws.core.ends.did_webs_resource_end import DIDWebsResourceEnd


def test_did_web_resource_end_on_get():
    req = mock(falcon.Request)
    rep = mock(falcon.Response)
    hby = mock(habbing.Habery)
    hby.kevers = {'test_aid': mock()}
    rgy = mock(credentialing.Regery)

    req.path = '/test_aid/did.json'
    req.host = 'example.com'
    req.port = 80
    req.get_header = lambda x: '80' if x == 'X-Forwarded-Port' else None

    when(didding).generate_did_doc(hby, rgy, 'did:web:example.com:test_aid', 'test_aid', meta=False).thenReturn(
        {'mocked': 'data'}
    )

    resource = DIDWebsResourceEnd(hby, rgy, False)
    resource.on_get(req, rep, 'test_aid')

    assert rep.status == falcon.HTTP_200
    assert rep.content_type == 'application/json'
    assert rep.data == b'{\n  "mocked": "data"\n}'

    unstub()


def test_did_web_resource_end_on_get_odd_port():
    req = mock(falcon.Request)
    rep = mock(falcon.Response)
    hby = mock(habbing.Habery)
    hby.kevers = {'test_aid': mock()}
    rgy = mock(credentialing.Regery)

    req.path = '/test_aid/did.json'
    req.host = 'example.com'
    req.port = 42
    req.get_header = lambda x: '42' if x == 'X-Forwarded-Port' else None

    when(didding).generate_did_doc(hby, rgy, 'did:web:example.com%3A42:test_aid', 'test_aid', meta=False).thenReturn(
        {'mocked': 'data'}
    )

    resource = DIDWebsResourceEnd(hby, rgy, False)
    resource.on_get(req, rep, 'test_aid')

    assert rep.status == falcon.HTTP_200
    assert rep.content_type == 'application/json'
    assert rep.data == b'{\n  "mocked": "data"\n}'

    unstub()


def test_did_web_resource_end_on_get_bad_path():
    req = mock(falcon.Request)
    rep = mock(falcon.Response)
    hby = mock(habbing.Habery)
    hby.kevers = {'test_aid': mock()}
    rgy = mock(credentialing.Regery)

    req.path = '/test_aid/bad.path'

    resource = DIDWebsResourceEnd(hby, rgy)

    with pytest.raises(falcon.HTTPBadRequest) as e:
        resource.on_get(req, rep, 'test_aid')

    assert isinstance(e.value, falcon.HTTPBadRequest)

    unstub()


def test_did_web_resource_end_on_get_bad_aid():
    req = mock(falcon.Request)
    rep = mock(falcon.Response)
    hby = mock(habbing.Habery)
    hby.kevers = {'test_aid': mock()}
    rgy = mock(credentialing.Regery)

    req.path = '/bad_aid/did.json'

    resource = DIDWebsResourceEnd(hby, rgy)

    with pytest.raises(falcon.HTTPNotFound) as e:
        resource.on_get(req, rep, 'bad_aid')

    assert isinstance(e.value, falcon.HTTPNotFound)

    unstub()
