"""
Part of the Aidlab Python SDK, providing the core functionality for scanning compatible devices.

To customise logging, configure the standard Python logging system in your
application, for example:

    logging.getLogger("aidlab.aidlab_manager").setLevel(logging.INFO)

Created by Szymon Gesicki on 09.05.2020.
"""

import logging

from .device import Device
from .transport import AidlabScanner, AidlabTransportFactory

logger = logging.getLogger(__name__)


class AidlabManager:
    """
    The central class of the Aidlab SDK for scanning compatible devices.
    """

    def __init__(
        self,
        scanner: AidlabScanner | None = None,
        transport_factory: AidlabTransportFactory | None = None,
    ):
        if scanner is None or transport_factory is None:
            try:
                from .bleak_adapter import BleakAidlabScanner, BleakTransportFactory
            except ImportError as exc:
                raise RuntimeError(
                    "Default BLE adapter requires the 'bleak' dependency. "
                    "Install it or provide custom scanner and transport_factory."
                ) from exc

        self._scanner = scanner if scanner is not None else BleakAidlabScanner()
        self._transport_factory = transport_factory if transport_factory is not None else BleakTransportFactory()

    async def scan(self, timeout: int = 10) -> list[Device]:
        """
        Scans for compatible devices.

        :param timeout: The time in seconds to scan for devices.
        """

        logger.info("Scanning for devices (timeout: %d seconds)...", timeout)

        devices = await self._scanner.scan(timeout)

        compatible_devices = [
            Device(
                address=device.address,
                name=device.name,
                transport=self._transport_factory.create(device),
            )
            for device in devices
        ]

        logger.info("Finished scanning. Found %d devices.", len(compatible_devices))

        return compatible_devices
