from typing import Union

from ._exceptions import SafePutException
from ._sessions import Session


class Store:
    def __init__(
            self,
            store_token: str,
            space_id: str,
            region: str,
            base_url: str = "https://store.huddu.io",
    ) -> None:
        """
        This class provides a simple way to interface with the **Store API** in python
        The endpoint for the store api is: https://store.huddu.io
        :param store_token:
        :param space_id:
        :param region:
        :param base_url:
        """
        self.session = Session(
            headers={
                "Authorization": f"Token {store_token}",
                "X-Space": space_id,
                "X-Region": region
            },
            base_url=base_url

        )

    def put(self, id: str, data: Union[list, str, dict, int], safe: bool = True) -> None:
        if safe:
            if self.get(id):
                raise SafePutException("Another entry with the same id already exists")

        self.session.request("POST", "/documents", data={
            "items": [{"id": id, "data": str(data)}]
        })

    def update(self, id: str, data: str) -> None:
        self.put(id, data, safe=False)

    def delete(self, id: str) -> None:
        self.session.request("DELETE", "/documents", data={
            "ids": [id]
        })

    def get(
            self,
            id: str
    ):
        res = self.session.request("GET", "/documents", params={
            "ids": id
        })["data"]

        if len(res) == 0:
            return None

        try:
            res = eval(res[0]["data"])
        except:
            res = res[0]["data"]
        return res
