import http.client
import base64


class OwnCloudClient:
    def __init__(
        self, host, username, password, remote_base_dir, port=None, method="https"
    ):
        self.host = host
        self.username = username
        self.password = password
        self.remote_base_dir = remote_base_dir

        self.port = port
        self.method = method
        self.conn = ...
        credentials = f"{username}:{password}"
        encoded_credentials = base64.b64encode(credentials.encode()).decode()
        self.encoded_credentials = encoded_credentials
        self.auth_header = f"Basic {encoded_credentials}"

    def _create_connection(self):
        port = self.port
        if self.method == "https":
            if port is None:
                port = 443
            self.conn = http.client.HTTPSConnection(self.host, port)
        elif self.method == "http":
            if port is None:
                port = 80
            self.conn = http.client.HTTPConnection(self.host, port)
        else:
            raise ValueError(f"not support {self.method}")

    def upload_file(
        self, data, remote_filename, content_type="application/octet-stream"
    ):
        """
        上传数据到 ownCloud。
        :param data: 要上传的数据，必须为 bytes 类型。如果是其他对象，请先转换为 bytes（例如 CSV 字符串 encode('utf-8')）
        :param remote_filename: 服务器端文件名（例如 "test.csv" 或 "image.png"），会自动拼接 remote_base_dir
        :param content_type: 可选，文件的 MIME 类型，默认为二进制流
        """
        self._create_connection()
        remote_path = f"{self.remote_base_dir}/{remote_filename}"
        headers = {
            "Authorization": self.auth_header,
            "Content-Length": str(len(data)),
            "Content-Type": content_type,
            "Connection": "keep-alive",
        }

        self.conn.request("PUT", remote_path, body=data, headers=headers)
        response = self.conn.getresponse()
        print("上传状态码:", response.status)
        print("原因:", response.reason)
        response_data = response.read()
        print("响应内容:", response_data.decode("utf-8", errors="ignore"))
        self.conn.close()

    def download_file_to_local(self, remote_filename, local_file_path):
        self._create_connection()
        remote_path = f"{self.remote_base_dir}/{remote_filename}"
        headers = {"Authorization": self.auth_header, "Connection": "keep-alive"}

        self.conn.request("GET", remote_path, headers=headers)
        response = self.conn.getresponse()
        print("下载状态码:", response.status)
        print("原因:", response.reason)
        file_data = response.read()

        with open(local_file_path, "wb") as f:
            f.write(file_data)
        print(f"文件已保存到: {local_file_path}")
        self.conn.close()


remote_base_dir = "/remote.php/dav/files/admin/scx"
client = OwnCloudClient(
    host="localhost",
    port=8080,
    method="http",
    username="admin",
    password="1234",
    remote_base_dir=remote_base_dir,
)
