import json

from cacheout import LFUCache
from tornado.httputil import url_concat
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPResponse

cache = LFUCache()  # clinet模块独立的缓存器


class HttpClient(object):
    def __init__(self) -> None:
        self.__headers = {}
        

    def set_header(self, herders: dict):
        self.__headers.update(herders)

    async def __client(self, _requests: HTTPRequest) -> HTTPResponse:
        httpClient = AsyncHTTPClient()
        r = await httpClient.fetch(_requests)
        return r
    
    async def post(self, url: str, body: dict, headers: dict, timeOut: int):
        if headers:
            self.set_header(headers)
        _requests = HTTPRequest(url=url,
                                method="POST",
                                body=json.dumps(body),
                                headers=self.__headers, request_timeout=timeOut,validate_cert=False)
        r = await self.__client(_requests)
        return r

    async def get(self, url: str, params: dict, headers: dict, timeOut: int):
        url = url_concat(url, params)
        if headers:
            self.set_header(headers)
        _requests = HTTPRequest(url=url,
                                method="GET",
                                headers=self.__headers, request_timeout=timeOut,validate_cert=False)
        r = await self.__client(_requests)
        return r