# Time    : 2024/8/12 11:57
# Author  : wangchao
# File    : HTTPClient.py
# Description : http工具类
import time
import requests
from requests.exceptions import HTTPError, Timeout, RequestException

class HTTPClient:
    def __init__(self, base_url, auth_token=None, headers=None, timeout=10):
        self.base_url = base_url
        self.auth_token = auth_token
        self.headers = headers if headers else {}
        self.timeout = timeout

        # 如果提供了认证token，添加到请求头
        if self.auth_token:
            self.headers['Authorization'] = f'Bearer {self.auth_token}'

    def get(self, endpoint, params=None):
        """发送GET请求"""
        response = requests.get(
            f"{self.base_url}/{endpoint}",
            params=params,
            headers=self.headers,
            timeout=self.timeout
        )
        return self._handle_response(response)

    def post(self, endpoint, data):
        """发送POST请求"""
        response = requests.post(
            f"{self.base_url}/{endpoint}",
            data=data,
            headers=self.headers,
            timeout=self.timeout
        )
        # 打印请求的详细信息
        #print("发送报文请求头：" + str(response.request.headers))
        #print("发送报文请求体：" + str(response.request.body))
        # 输出响应内容
        #print('Post Status Code:', response.status_code)
        #print('Post Response Body:', response.text)

        return self._handle_response(response)

    def put(self, endpoint, data):
        """发送PUT请求"""
        response = requests.put(
            f"{self.base_url}/{endpoint}",
            json=data,
            headers=self.headers,
            timeout=self.timeout
        )
        # 输出响应内容
        #print('Put Status Code:', response.status_code)
        #print('Put Response Body:', response.text)

        return self._handle_response(response)

    def delete(self, endpoint):
        """发送DELETE请求"""
        response = requests.delete(
            f"{self.base_url}/{endpoint}",
            headers=self.headers,
            timeout=self.timeout
        )
        return self._handle_response(response)

    def _handle_response(self, response):
        """处理HTTP响应"""
        try:
            response.raise_for_status()  # 检查请求是否成功
            return response.json() if response.content else {}  # 返回JSON数据或空字典

        except HTTPError as http_err:
            print(f"HTTP error occurred: {http_err}")  # 提示HTTP错误
        except Timeout:
            print("The request timed out")  # 处理超时
        except RequestException as req_err:
            print(f"Request error occurred: {req_err}")  # 处理其他请求错误
        except ValueError:
            print("Non-JSON response received")  # 处理非JSON响应
        return None  # 返回None表示出错

# 使用示例
if __name__ == "__main__":
    # 创建HTTP客户端
    client = HTTPClient(
        "http://192.168.1.188:18000",
        auth_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiU3VwZXJBZG1pbiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWVpZGVudGlmaWVyIjoiU3VwZXJBZG1pbiIsImV4cCI6MTcxMDkwMTU0MywiaXNzIjoiQ01TdjIiLCJhdWQiOiJBcGkifQ.ViXzrmAU2txWVQyHkr-dA7wUo9ezntrzdTmJhS9Vv7k",  # 替换为你的认证token (如需要)
        headers={"Content-Type": "application/x-www-form-urlencoded"},  # 设置请求头
        timeout=10  # 设置超时时间为5秒
    )

    project_name = "demo测试工程" + str(int(time.time()))
    # 创建资源
    try:
        create_response = client.post("api/v1/project/node", {"name": f"{project_name}", "path": "", "type": "1"})
        print("Create Response:", create_response)

    except Exception as e:
        print("Error creating resource:", e)

    # # 读取资源
    # try:
    #     read_response = client.get("items", params={"id": 1})
    #     print("Read Response:", read_response)
    # except Exception as e:
    #     print("Error reading resource:", e)
    #
    # # 更新资源
    # try:
    #     update_response = client.put("items/1", {"name": "Updated Item", "description": "Updated description"})
    #     print("Update Response:", update_response)
    # except Exception as e:
    #     print("Error updating resource:", e)
    #
    # # 删除资源
    # try:
    #     delete_response = client.delete("items/1")
    #     print("Delete Response:", delete_response)
    # except Exception as e:
    #     print("Error deleting resource:", e)