import requests
import json
from django.conf import settings
from requests.auth import HTTPBasicAuth


class APIHandler:
    def __init__(self):
        self._organisation_id = None

    def call_api(self, url):
        return requests.get(url, auth=HTTPBasicAuth(
            settings.API_BASIC_USERNAME, settings.API_BASIC_PASSWORD
        ))

    def get_themes(self):
        url = "{}/api/organisations/{}/themes/".format(
            settings.BO_API_URL, self.organisation_id
        )
        response = self.call_api(url)
        response.raise_for_status()
        return response.json()

    def check_qrcode_validity(self, token):
        url = "{}/api/organisations/{}/user/{}/".format(
            settings.BO_API_URL, self.organisation_id, token
        )
        response = self.call_api(url)
        response.raise_for_status()
        return response.json()

    def get_configuration(self, serial_number):
        url = "{}/api/chairs/{}".format(settings.BO_API_URL, serial_number)
        response = self.call_api(url)
        response.raise_for_status()
        return response.json()

    @property
    def organisation_id(self):
        if not self._organisation_id:
            with open(settings.CONFIG_FILE_PATH, 'r') as config_file:
                json_conf = json.load(config_file)
                self._organisation_id = json_conf['organisation_id']
        return self._organisation_id
