import os
import logging

from homeassistant import config_entries

from .const import DOMAIN, DEVICES_DIR

_LOGGER = logging.getLogger(__name__)


class SmS4IoTConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
    """Config flow: redirects to a QR-scanner page, then creates the entry."""

    VERSION = 1

    def __init__(self):
        self._device_data: dict = {}

    async def async_step_user(self, user_input=None):
        """Open the QR-scanner page in a new window."""
        return self.async_external_step(
            step_id="scan",
            url=f"/sms4iot_static/scanner.html?flow_id={self.flow_id}",
        )

    async def async_step_scan(self, user_input=None):
        """Receive QR data posted by the scanner page."""
        if not user_input or "qr_data" not in user_input:
            return self.async_abort(reason="missing_qr_data")

        #_LOGGER.warning("async_step_scan: user_input:" + user_input["qr_data"])
        # key may have a leading " " space that is used in s4igw.c/base45
        #parts = user_input["qr_data"].strip().split()
        parts = user_input["qr_data"].split()  # doesnt handle double space right
        if len(parts) < 3:
            return self.async_abort(reason="invalid_qr_format")

        device_id, domain_name, protocol = parts[0], parts[1], parts[2]
        keys = parts[3:]

        await self.async_set_unique_id(device_id)
        self._abort_if_unique_id_configured()

        devices_dir = self.hass.config.path(DEVICES_DIR)
        os.makedirs(devices_dir, exist_ok=True)
        #raw_line = " ".join(parts)
        raw_line = user_input["qr_data"]
        
        def _write():
            with open(os.path.join(devices_dir, device_id), "w") as fh:
                fh.write(raw_line)

        await self.hass.async_add_executor_job(_write)

        self._device_data = {
            "device_id": device_id,
            "domain_name": domain_name,
            "protocol": protocol,
            "keys": keys,
        }        
        _LOGGER.warning("async_step_scan")
        return self.async_external_step_done(next_step_id="finish")

    async def async_step_finish(self, user_input=None):
        """Create the config entry after a successful scan."""
        _LOGGER.warning("async_step_finish")
        return self.async_create_entry(
            title=f"SMS4IoT {self._device_data['device_id']}",
            data=self._device_data,
        )
