from ..registry import registry


def get_iot_urlpatterns(prefix="things"):
    """Generate DRF URL patterns for all registered device types.

    Usage in urls.py::

        from django_devicehub.generators.urls import get_iot_urlpatterns

        urlpatterns = [
            ...
            *get_iot_urlpatterns("api/things"),
        ]
    """
    try:
        from rest_framework.routers import DefaultRouter
    except ImportError:
        return []

    from .views import create_viewsets

    router = DefaultRouter()

    for dt_cls in registry.all():
        if dt_cls._device_model is None:
            continue

        type_name = dt_cls.__name__.lower()
        DeviceViewSet, ReadingViewSet = create_viewsets(dt_cls)

        if DeviceViewSet:
            router.register(
                f"{prefix}/{type_name}/devices",
                DeviceViewSet,
                basename=f"{type_name}-device",
            )
        if ReadingViewSet:
            router.register(
                f"{prefix}/{type_name}/readings",
                ReadingViewSet,
                basename=f"{type_name}-reading",
            )

    return router.urls
