"""
NotifierWebsocket

@ Author: Antonio Bevilacqua, Paolo Saviano
@ Email: abevilacqua@meetecho.com, psaviano@meetecho.com

Transmit message to a websocket socket.
"""

import threading

from websockets.sync.client import connect

from juturna.components import Message
from juturna.components import Node

from juturna.payloads import BasePayload


class NotifierWebsocket(Node[BasePayload, None]):
    """Transmit data to a websocket endpoint"""

    def __init__(self, endpoint: str, **kwargs):
        """
        Parameters
        ----------
        endpoint : str
            Destination endpoint, including port.
        kwargs : dict
            Superclass arguments.

        """
        super().__init__(**kwargs)

        self._endpoint = endpoint

        self._sent = 0
        self._t = None

    def warmup(self):
        """Warmup the node"""
        self.logger.info(f'[{self.name}] set to endpoint {self._endpoint}')

    def update(self, message: Message[BasePayload]):
        """Receive a message, transmit a message"""
        meta = dict(message.meta)
        to_send = Message[BasePayload](
            creator=message.creator,
            version=message.version,
            payload=message.payload,
        )

        meta['session_id'] = self.pipe_id
        to_send.meta = meta

        self._t = threading.Thread(
            name='_post_transcript',
            target=self._send_message,
            args=(to_send,),
            daemon=True,
        )

        self._t.start()

        self._sent += 1

    def _send_message(self, message: Message[BasePayload]):
        with connect(self._endpoint) as ws:
            try:
                message_json = message.to_json()
                ws.send(message_json)
            except Exception as e:
                self.logger.warning(e)

    def destroy(self):
        """Destroy the node"""
        if self._t:
            self._t.join()
        ...
