import json

from websocket import create_connection, WebSocketConnectionClosedException

from core.dict_object import DictObject
from core.logger import Logger


class WebsocketRelayWorker:
    def __init__(self, inbound_queue, url, auth):
        self.logger = Logger(__name__)
        self.inbound_queue = inbound_queue
        self.url = url
        self.auth = auth
        self.ws = None

    def run(self):
        try:
            self.ws = create_connection(self.url)
            self.logger.info(f"Connected to Datanet Relay!")
            self.inbound_queue.append(DictObject({"type": "connected"}))

            result = self.ws.recv()
            while result:
                if result == "#auth":
                    self.ws.send(self.auth)
                else:
                    obj = DictObject(json.loads(result))
                    self.inbound_queue.append(obj)
                result = self.ws.recv()
            self.ws.close()
        except ConnectionRefusedError:
            pass
        except ConnectionResetError:
            pass
        except WebSocketConnectionClosedException:
            pass

    def send_message(self, message):
        if self.ws:
            self.ws.send(message)

    def close(self):
        if self.ws:
            self.ws.close()
