"""Test the wmspro initialization."""

from pathlib import Path
from unittest.mock import AsyncMock

import aiohttp
import pytest
from syrupy.assertion import SnapshotAssertion

from homeassistant.components.wmspro.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.storage import STORAGE_DIR

from . import remove_config_entry, setup_config_entry, unload_config_entry

from tests.common import MockConfigEntry


async def test_config_entry_device_config_ping_failed(
    hass: HomeAssistant,
    mock_config_entry: MockConfigEntry,
    mock_hub_ping: AsyncMock,
) -> None:
    """Test that a config entry will be retried due to ConfigEntryNotReady."""
    mock_hub_ping.side_effect = aiohttp.ClientError
    assert not await setup_config_entry(hass, mock_config_entry)
    assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
    assert len(mock_hub_ping.mock_calls) == 1


async def test_config_entry_device_config_refresh_failed(
    hass: HomeAssistant,
    mock_config_entry: MockConfigEntry,
    mock_hub_ping: AsyncMock,
    mock_hub_refresh: AsyncMock,
) -> None:
    """Test that a config entry will be retried due to ConfigEntryNotReady."""
    mock_hub_refresh.side_effect = aiohttp.ClientError
    assert not await setup_config_entry(hass, mock_config_entry)
    assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
    assert len(mock_hub_ping.mock_calls) == 1
    assert len(mock_hub_refresh.mock_calls) == 1


async def test_config_entry_persistent_storage(
    hass: HomeAssistant,
    mock_config_entry: MockConfigEntry,
    mock_hub_ping: AsyncMock,
    mock_hub_refresh: AsyncMock,
) -> None:
    """Test that a config entry will use and cleanup persistent storage."""
    config_dir = Path(
        hass.config.path(STORAGE_DIR, f"{DOMAIN}-{mock_config_entry.entry_id}")
    )

    assert await setup_config_entry(hass, mock_config_entry)
    assert len(mock_hub_ping.mock_calls) == 1
    assert len(mock_hub_refresh.mock_calls) == 1
    assert config_dir.is_dir()  # created during setup

    assert await unload_config_entry(hass, mock_config_entry)
    assert config_dir.is_dir()  # NOT removed, but kept during unload

    assert await remove_config_entry(hass, mock_config_entry)
    assert not config_dir.is_dir()  # removed during removal


@pytest.mark.parametrize(
    ("mock_hub_configuration", "mock_hub_status"),
    [
        ("config_prod_awning_dimmer.json", "status_prod_awning.json"),
        ("config_prod_awning_dimmer.json", "status_prod_dimmer.json"),
        ("config_prod_roller_shutter.json", "status_prod_roller_shutter.json"),
    ],
    indirect=True,
)
async def test_device_setup(
    hass: HomeAssistant,
    mock_config_entry: MockConfigEntry,
    mock_hub_ping: AsyncMock,
    mock_hub_configuration: AsyncMock,
    mock_hub_status: AsyncMock,
    device_registry: dr.DeviceRegistry,
    snapshot: SnapshotAssertion,
) -> None:
    """Test that the device is created correctly."""
    assert await setup_config_entry(hass, mock_config_entry)
    assert len(mock_hub_ping.mock_calls) == 1
    assert len(mock_hub_configuration.mock_calls) == 1
    assert len(mock_hub_status.mock_calls) == len(mock_hub_configuration.destinations)

    device_entries = device_registry.devices.get_devices_for_config_entry_id(
        mock_config_entry.entry_id
    )
    assert len(device_entries) > len(mock_hub_configuration.destinations)

    hub_device_entry = device_registry.async_get_device_by_identifier(
        (DOMAIN, mock_config_entry.entry_id), mock_config_entry.entry_id
    )
    assert hub_device_entry is not None

    device_entries = list(
        filter(
            lambda e: e.identifiers != {(DOMAIN, mock_config_entry.entry_id)},
            device_entries,
        )
    )
    assert len(device_entries) >= len(mock_hub_configuration.destinations)
    for device_entry in device_entries:
        assert device_entry.via_device_id == hub_device_entry.id
        assert device_entry == snapshot(name=f"device-{device_entry.serial_number}")
