import json
import logging
import queue
import threading

import urllib.request

logger = logging.getLogger('wevitos')


class Transport:
    """Non-blocking transport that sends payloads in a daemon thread."""

    def __init__(self, url, api_key):
        self.url = url
        self.api_key = api_key
        self._queue = queue.Queue(maxsize=100)
        self._worker = threading.Thread(target=self._run, daemon=True)
        self._worker.start()

    def send(self, payload):
        try:
            self._queue.put_nowait(payload)
        except queue.Full:
            logger.warning('wevitos: send queue full, dropping event')

    def _run(self):
        while True:
            payload = self._queue.get()
            try:
                self._do_send(payload)
            except Exception:
                logger.debug('wevitos: failed to send event', exc_info=True)

    def _do_send(self, payload):
        data = json.dumps(payload).encode('utf-8')
        req = urllib.request.Request(
            self.url,
            data=data,
            headers={
                'Content-Type': 'application/json',
                'X-API-Key': self.api_key,
            },
            method='POST',
        )
        try:
            with urllib.request.urlopen(req, timeout=10) as resp:
                pass
        except Exception:
            logger.debug('wevitos: HTTP error sending event', exc_info=True)
