import requests  # TODO avoid requests
from . import Socket
from .zmq import ZMQCurveSocketFactory


class HTTPSocket(Socket):
    def connect(self, ip_addr):
        self.url = "http://{:s}/tweaks/raw".format(ip_addr)
        self._session = requests.Session()

    def transfer(self, data, timeout=1000):
        r = self._session.post(self.url, data=data, timeout=timeout / 1000.0)
        return r.content


class HTTPRenderSocket(HTTPSocket):
    def transfer(self, data):
        resp = super().transfer(b'\x57' + data)
        assert resp[:2] == b'\x57\x00'
        return resp[2:]


class HTTPSocketFactory(ZMQCurveSocketFactory):
    def getControlSocket(self):
        skt = HTTPSocket()
        skt.connect(self.addr)
        return skt

    def getRenderSocket(self):
        skt = HTTPRenderSocket()
        skt.connect(self.addr)
        return skt
