import json
import requests

from login import LoginApi


class Api:
    def __init__(self, collection_name: str, ):
        self.access_token: str
        self.collection_name = collection_name
        self.api_basepath = "http://127.0.0.1:8090/api"
        self.email = "juliancuni@gmail.com"
        self.password = "MatraPaPuPa..11"

        login = LoginApi(email=self.email, password=self.password).login()
        self.access_token = login["token"]

    def list_collection(self, filter=""):
        url = f"{self.api_basepath}/collections/{self.collection_name}/records?{filter}"
        res = requests.get(url=url, headers={
                           'Authorization': f'Admin {self.access_token}'})
        return res.json()

    def create_collection(self, obj, filter=""):
        url = f"{self.api_basepath}/collections/{self.collection_name}/records"
        exists = self.list_collection(filter=filter)
        if len(exists["items"]) > 0:
            return exists
        else:
            try:
                # obj = json.dumps(obj, allow_nan=False)
                print('saving')
                res = requests.post(url=url, json=obj, headers={
                                    'Authorization': f'Admin {self.access_token}'})
                return res.json()
            except ValueError as e:
                print(e)
                print(obj)
                return None
        return None
