"""Config flow for simplepush integration."""
from __future__ import annotations

import logging
from typing import Any

from simplepush import UnknownError, send, send_encrypted
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_NAME, CONF_PASSWORD
from homeassistant.data_entry_flow import FlowResult

from .const import ATTR_ENCRYPTED, CONF_DEVICE_KEY, CONF_SALT, DEFAULT_NAME, DOMAIN

_LOGGER = logging.getLogger(__name__)


def validate_input(entry: dict[str, str]) -> dict[str, str] | None:
    """Validate user input."""
    try:
        if CONF_PASSWORD in entry:
            send_encrypted(
                entry[CONF_DEVICE_KEY],
                entry[CONF_PASSWORD],
                entry[CONF_PASSWORD],
                "HA test",
                "Message delivered successfully",
            )
        else:
            send(entry[CONF_DEVICE_KEY], "HA test", "Message delivered successfully")
    except UnknownError:
        return {"base": "cannot_connect"}

    return None


class SimplePushFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle a config flow for simplepush."""

    async def async_step_user(
        self, user_input: dict[str, Any] | None = None
    ) -> FlowResult:
        """Handle a flow initiated by the user."""
        errors: dict[str, str] | None = None
        if user_input is not None:

            await self.async_set_unique_id(user_input[CONF_DEVICE_KEY])
            self._abort_if_unique_id_configured()

            self._async_abort_entries_match(
                {
                    CONF_NAME: user_input[CONF_NAME],
                }
            )

            if not (
                errors := await self.hass.async_add_executor_job(
                    validate_input, user_input
                )
            ):
                return self.async_create_entry(
                    title=user_input[CONF_NAME],
                    data=user_input,
                )

        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema(
                {
                    vol.Required(CONF_DEVICE_KEY): str,
                    vol.Required(CONF_NAME, default=DEFAULT_NAME): str,
                    vol.Inclusive(CONF_PASSWORD, ATTR_ENCRYPTED): str,
                    vol.Inclusive(CONF_SALT, ATTR_ENCRYPTED): str,
                }
            ),
            errors=errors,
        )

    async def async_step_import(self, import_config: dict[str, str]) -> FlowResult:
        """Import a config entry from configuration.yaml."""
        _LOGGER.warning(
            "Configuration of the simplepush integration in YAML is deprecated and "
            "will be removed in a future release; Your existing configuration "
            "has been imported into the UI automatically and can be safely removed "
            "from your configuration.yaml file"
        )
        return await self.async_step_user(import_config)
