"""The tests for the REST switch platform."""
import asyncio
from http import HTTPStatus

import aiohttp

from homeassistant.components.rest import DOMAIN
import homeassistant.components.rest.switch as rest
from homeassistant.components.switch import DEVICE_CLASS_SWITCH, DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
    CONF_HEADERS,
    CONF_NAME,
    CONF_PARAMS,
    CONF_PLATFORM,
    CONF_RESOURCE,
    CONTENT_TYPE_JSON,
)
from homeassistant.helpers.template import Template
from homeassistant.setup import async_setup_component

from tests.common import assert_setup_component

"""Tests for setting up the REST switch platform."""

NAME = "foo"
DEVICE_CLASS = DEVICE_CLASS_SWITCH
METHOD = "post"
RESOURCE = "http://localhost/"
STATE_RESOURCE = RESOURCE
AUTH = None
PARAMS = None


async def test_setup_missing_config(hass):
    """Test setup with configuration missing required entries."""
    assert not await rest.async_setup_platform(hass, {CONF_PLATFORM: DOMAIN}, None)


async def test_setup_missing_schema(hass):
    """Test setup with resource missing schema."""
    assert not await rest.async_setup_platform(
        hass,
        {CONF_PLATFORM: DOMAIN, CONF_RESOURCE: "localhost"},
        None,
    )


async def test_setup_failed_connect(hass, aioclient_mock):
    """Test setup when connection error occurs."""
    aioclient_mock.get("http://localhost", exc=aiohttp.ClientError)
    assert not await rest.async_setup_platform(
        hass,
        {CONF_PLATFORM: DOMAIN, CONF_RESOURCE: "http://localhost"},
        None,
    )


async def test_setup_timeout(hass, aioclient_mock):
    """Test setup when connection timeout occurs."""
    aioclient_mock.get("http://localhost", exc=asyncio.TimeoutError())
    assert not await rest.async_setup_platform(
        hass,
        {CONF_PLATFORM: DOMAIN, CONF_RESOURCE: "http://localhost"},
        None,
    )


async def test_setup_minimum(hass, aioclient_mock):
    """Test setup with minimum configuration."""
    aioclient_mock.get("http://localhost", status=HTTPStatus.OK)
    with assert_setup_component(1, SWITCH_DOMAIN):
        assert await async_setup_component(
            hass,
            SWITCH_DOMAIN,
            {
                SWITCH_DOMAIN: {
                    CONF_PLATFORM: DOMAIN,
                    CONF_RESOURCE: "http://localhost",
                }
            },
        )
        await hass.async_block_till_done()
    assert aioclient_mock.call_count == 1


async def test_setup_query_params(hass, aioclient_mock):
    """Test setup with query params."""
    aioclient_mock.get("http://localhost/?search=something", status=HTTPStatus.OK)
    with assert_setup_component(1, SWITCH_DOMAIN):
        assert await async_setup_component(
            hass,