"""The tests for the InfluxDB component."""
import unittest
from unittest import mock

import influxdb as influx_client

from homeassistant.setup import setup_component
import homeassistant.components.influxdb as influxdb
from homeassistant.const import EVENT_STATE_CHANGED, STATE_OFF, STATE_ON

from tests.common import get_test_home_assistant


@mock.patch('influxdb.InfluxDBClient')
class TestInfluxDB(unittest.TestCase):
    """Test the InfluxDB component."""

    def setUp(self):
        """Setup things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        self.handler_method = None
        self.hass.bus.listen = mock.Mock()

    def tearDown(self):
        """Clear data."""
        self.hass.stop()

    def test_setup_config_full(self, mock_client):
        """Test the setup with full configuration."""
        config = {
            'influxdb': {
                'host': 'host',
                'port': 123,
                'database': 'db',
                'username': 'user',
                'password': 'password',
                'ssl': 'False',
                'verify_ssl': 'False',
            }
        }
        assert setup_component(self.hass, influxdb.DOMAIN, config)
        self.assertTrue(self.hass.bus.listen.called)
        self.assertEqual(
            EVENT_STATE_CHANGED, self.hass.bus.listen.call_args_list[0][0][0])
        self.assertTrue(mock_client.return_value.query.called)

    def test_setup_config_defaults(self, mock_client):
        """Test the setup with default configuration."""
        config = {
            'influxdb': {
                'host': 'host',
                'username': 'user',
                'password': 'pass',
            }
        }
        assert setup_component(self.hass, influxdb.DOMAIN, config)
        self.assertTrue(self.hass.bus.listen.called)
        self.assertEqual(
            EVENT_STATE_CHANGED, self.hass.bus.listen.call_args_list[0][0][0])

    def test_setup_minimal_config(self, mock_client):
        """Test the setup with minimal configuration."""
        config = {
            'influxdb': {}
        }

        assert setup_component(self.hass, influxdb.DOMAIN, config)

    def test_setup_missing_password(self, mock_client):
        """Test the setup with existing username and missing password."""
        config = {
            'influxdb': {
                'username': 'user'
            }
        }

        assert not setup_component(self.hass, influxdb.DOMAIN, config)

    def test_setup_query_fail(self, mock_client):
        """Test the setup for query failures."""
        config = {
            'influxdb': {
                'host': 'host',
                'username': 'user',
                'password': 'pass',
            }
        }
        mock_client.return_value.query.side_effect = \
            influx_client.exceptions.InfluxDBClientError('fake')
        assert not setup_component(self.hass, influxdb.DOMAIN, config)

    def _setup(self):
        """Setup the client."""
        config = {
            'influxdb': {
                'host': 'host',
                'username': 'user',
                'password': 'pass',
                'exclude': {
                    'entities': ['fake.blacklisted'],
                    'domains': ['another_fake']
                }
            }
        }
        assert setup_component(self.hass, influxdb.DOMAIN, config)
        self.handler_method = self.hass.bus.listen.call_args_list[0][0][1]

    def test_event_listener(self, mock_client):
        """Test the event listener."""
        self._setup()

        valid = {
            '1': 1,
            '1.0': 1.0,
            STATE_ON: 1,
            STATE_OFF: 0,
            'foo': 'foo'
        }
        for in_, out in valid.items():
            attrs = {
                'unit_of_measurement': 'foobars',
                'longitude': '1.1',
                'latitude': '2.2'
            }
            state = mock.MagicMock(
                state=in_, domain='fake', object_id='entity', attributes=attrs)
            event = mock.MagicMock(data={'new_state': state}, time_fired=12345)
            if isinstance(out, str):
                body = [{
                    'measurement': 'foobars',
                    'tags': {
                        'domain': 'fake',
                        'entity_id': 'entity',
                    },
                    'time': 12345,
                    'fields': {
                        'state': out,
                        'longitude': 1.1,
                        'latitude': 2.2
                    },
                }]

            else:
                body = [{