import json

import requests
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPResponse


class HttpClient(object):
    def __init__(self) -> None:
        super().__init__()
        self._host = ""
        self._port = 0
        self._headers = {}

    @property
    def host(self):
        return

    @host.setter
    def host(self, value):
        self._host = value

    @property
    def port(self):
        return

    @port.setter
    def port(self, value):
        if not isinstance(value, int):
            return TypeError(f"端口必须是一个int:{value}")
        self._port = value

    @property
    def headers(self):
        return

    @headers.setter
    def headers(self, value):
        self._headers = value


class RequestClient(HttpClient):
    def __init__(self) -> None:
        super(RequestClient, self).__init__()

    def post(self, api, body, timeOut):
        r = requests.post(api, json.dumps(body), timeout=timeOut, headers=self._headers)
        return r.json()


class AsyncRequestClient(HttpClient):
    def __init__(self) -> None:
        super(AsyncRequestClient, self).__init__()

    async def __req(self, _requests: HTTPRequest) -> HTTPResponse:
        httpClient = AsyncHTTPClient()
        r = await httpClient.fetch(_requests)
        return r

    async def post(self, url, body, timeOut):
        _requests = HTTPRequest(url=url,
                                method="POST",
                                body=json.dumps(body),
                                headers=self._headers, request_timeout=timeOut)
        r = await self.__req(_requests)
        return r
