
import json
from retrying_async import retry
from cacheout import LFUCache
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPResponse
# from jpype import JClass, getDefaultJVMPath, startJVM, isJVMStarted

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


# class Jar(object):
#     def __init__(self) -> None:
#         super(Jar,self).__init__()
#         self._path = "-Djava.class.path=/lib/gmssl-jar/gmsse-1.3.0-jar-with-dependencies.jar"
#         self._jarClass = ""
#         self._stream = None

    
#     @property
#     def jarClass(self):
#         return self._jarClass

#     @jarClass.setter
#     def jarClass(self, value):
#         self._jarClass = value


#     @property
#     def stream(self):
#         return self._stream

#     @property
#     def path(self):
#         return self._path

#     @path.setter
#     def param(self, value):
#         self._path = value

#     def conn(self):
#         if not isJVMStarted():
#             jvmPath = getDefaultJVMPath()
#             startJVM(jvmPath, self._path, convertStrings=False)
#             print("开机一次")
#         self._stream = JClass(self._jarClass)

# jarhttpClient = Jar()
# jarhttpClient.jarClass = "com.aliyun.gmsse.doConnect.DoHttpsConnect"
# jarhttpClient.conn()

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
    
    @retry(attempts=3, delay=0.1)
    async def post(self, url: str, body: dict, headers: dict, timeOut: int):
        if headers:
            self.set_header(headers)
        # url = url_concat(f"{self.protocol}://{self.host}{self.port}{url}", dict(_time=str(int(time.time()))))
        _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