import logging
from cent import Client, PublishRequest
from django.conf import settings
from typing import Any

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
class LogToWS:
    _channel = 'public'

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        self.publish_ws = kwargs.pop('publish_ws', True) and not settings.DEVELOPMENT
        self.channel = kwargs.pop('channel', self._channel)
        self.ws_client = None
        if self.publish_ws:
            try:
                self.ws_client = Client(
                    api_url=f'http://localhost:{settings.WEBSOCKET_PORT}/api',
                    api_key=settings.CENTRIFUGE_API_KEY,
                )
            except Exception as e:
                logger.exception('Unable to reach websocket server: %s', e)

    def publish(self, data: dict) -> None:
        """
        Publish data to websocket server if it's reachable.
        """
        if not self.publish_ws or not self.ws_client:
            return

        try:
            self.ws_client.publish(PublishRequest(channel=self.channel, data=data))
        except Exception as e:
            if settings.DEBUG:
                print(f'Unable to publish {data} to Websocket Server: {e}')
            logger.error('Unable to publish %s to Websocket Server: %s', data, e)

    def publish_line(self, line: str, **kwargs: Any) -> None:
        """
        Send line to websocket server if it's reachable.
        """
        data = kwargs or {}
        data['line'] = line
        self.publish(data)


__all__ = [
    'LogToWS',
]
