import requests
from ..types.dataclass import file as bfile
from requests_toolbelt import MultipartEncoder
from typing import Any


class Client:
    def __init__(self, session: requests.Session, url: str):
        self.session = session
        self.url = url

    def post_form(self, url: str, params: bfile.Param) -> (Any, Exception):
        multipart_fields = {}
        if params.files:
            for pf in params.files:
                multipart_fields[pf.key] = (
                    pf.name,
                    open(pf.path, "rb"),
                    "multipart/form-data",
                )

        if params.data:
            for pd in params.data:
                multipart_fields[pd.key] = pd.value

        encoder = MultipartEncoder(fields=multipart_fields)
        headers = {"Content-Type": encoder.content_type}

        try:
            response = self.session.post(url, data=encoder, headers=headers)
            response.raise_for_status()
            return response.json(), None
        except Exception as e:
            return None, e


def new_client(url, token, timeout):
    try:
        # Create a session object with a bearer token in the headers
        session = requests.Session()
        headers = {"authorization": f"Bearer {token}"}
        session.headers.update(headers)

        # Set timeout if it is greater than 0
        if timeout > 0:
            session.timeout = timeout

        return Client(session, url)
    except Exception as e:
        # Handle any exceptions during client initialization
        return f"Error during client initialization:", {e}
