# -*- coding: utf-8 -*-
from unittest import mock


async def test_save_frontend_state(homehub_app, homehub_client):
    # Given
    fake_state = {
        'backend': {
            'spam': True,
        },
        'frontend': {
            'eggs': True,
        },
    }

    payload = {'new': True}

    state_to_save = {
        'backend': {
            'spam': True,
        },
        'frontend': payload,
    }

    with mock.patch.object(homehub_app['STATE'], 'get') as mock_state_get:
        with mock.patch.object(homehub_app['STATE'], 'save'):
            with mock.patch.object(homehub_app, 'notify_subscribers'):
                mock_state_get.return_value = fake_state

                # When
                response = await homehub_client.post('/backend/rpc', json={
                    'jsonrpc': '2.0',
                    'id': 'testing',
                    'method': 'state.save_frontend',
                    'params': [payload],
                })

                # Then
                assert response.status == 200

                data = await response.json()
                assert data['result'] is True
                assert 'error' not in data

                homehub_app['STATE'].save.assert_called_with(state_to_save)
                homehub_app.notify_subscribers.assert_called_with({
                    'type': 'STATE_NOTIFICATION',
                    'data': payload,
                })
