import logging
from typing import Optional, Dict

import requests
from requests import Response

logger = logging.getLogger(__name__)


class bagSyHub:
    def __init__(self, username: str, instance_url: str, token: str):
        self.url = f"http://{instance_url}/api"
        self.authorization = f"{username}@{token}"

    @staticmethod
    def __process_response__(res: Response) -> Optional[Dict]:
        if res.status_code == 500:
            logger.fatal("Unknown server error occurred.")
            return None
        try:
            json = res.json()
            if res.status_code == 200:
                return json
            elif "error" in json:
                logger.error(f"Error occurred ({res.status_code}): {res.json()['error']}")
            else:
                logger.error(f"Error occurred ({res.status_code}).")
        except:
            logger.fatal("Could not parse server's response.")
            logger.debug(f"Content is: '{res.content}'")
            return None

    def get(self, path: str, headers: Optional[Dict[str, str]] = None) -> Optional[Dict]:
        r = requests.get(f"{self.url}{path}",
                         headers={**(headers or {}),
                                  "Authorization": f"Bearer {self.authorization}"})
        return self.__process_response__(r)

    def post(self, path: str, json=None, data=None, headers: Optional[Dict[str, str]] = None) -> Optional[Dict]:
        r = requests.post(f"{self.url}{path}",
                          headers={**(headers or {}),
                                   "Authorization": f"Bearer {self.authorization}"},
                          data=data,
                          json=json)
        return self.__process_response__(r)
