# -*- coding: utf-8 -*-
from homehub_backend.testing import services as testing_services


class Test_UseService:
    async def test_unknown_service_instance(self, homehub_client):
        response = await homehub_client.post('/backend/rpc', json={
            'jsonrpc': '2.0',
            'id': 'testing',
            'method': 'services.use',
            'params': [
                'testing.FakeService', 'idontexist', 'capability',
                ['It works!'],
            ],
        })
        assert response.status == 200

        data = await response.json()
        assert 'result' not in data
        assert data['error']['data'] == (
            'Unknown service: idontexist of testing.FakeService'
        )

    async def test_unknown_service_kind(self, homehub_client):
        response = await homehub_client.post('/backend/rpc', json={
            'jsonrpc': '2.0',
            'id': 'testing',
            'method': 'services.use',
            'params': [
                'IDontExist', 'fake_instance', 'capability',
                ['It works!'],
            ],
        })
        assert response.status == 200

        data = await response.json()
        assert 'result' not in data
        assert data['error']['data'] == 'Unknown service: IDontExist'

    async def test_unknown_capability(self, homehub_client):
        service = testing_services.FakeService(
            homehub_client.server.app, 'fake_instance', {},
        )
        homehub_client.server.app['SERVICES'].update({
            'testing.FakeService.fake_instance': service,
        })

        response = await homehub_client.post('/backend/rpc', json={
            'jsonrpc': '2.0',
            'id': 'testing',
            'method': 'services.use',
            'params': [
                'testing.FakeService', 'fake_instance', 'idontexist',
                ['It works!'],
            ],
        })
        assert response.status == 200

        data = await response.json()
        assert 'result' not in data
        assert data['error']['data'] == (
            'Unknown capability: testing.FakeService.idontexist'
        )

    async def test_ok(self, homehub_client):
        service = testing_services.FakeService(
            homehub_client.server.app, 'fake_instance', {},
        )
        service.register_capability('capability', service.capability)

        homehub_client.server.app['SERVICES'].update({
            'testing.FakeService.fake_instance': service,
        })

        response = await homehub_client.post('/backend/rpc', json={
            'jsonrpc': '2.0',
            'id': 'testing',
            'method': 'services.use',
            'params': [
                'testing.FakeService', 'fake_instance', 'capability',
                ['It works!'],
            ],
        })
        assert response.status == 200

        data = await response.json()
        assert data['result'] == 'It works!'
        assert 'error' not in data
