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


def read_config(key):
    with open(settings.CONFIG_FILE_PATH, 'r') as config_file:
        json_conf = json.load(config_file)
        return json_conf[key]


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

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

    def send_to_api(self, url, data):
        return requests.post(url, data=data, 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()

    def send_music_session(self, session_info):
        url = "{}/api/chairs/{}/sessions/".format(
            settings.BO_API_URL, self.serial_number
        )
        response = self.send_to_api(url, session_info)
        response.raise_for_status()
        return response.json()

    @property
    def organisation_id(self):
        if not self._organisation_id:
            self._organisation_id = read_config('organisation_id')
        return self._organisation_id

    @property
    def serial_number(self):
        if not self._serial_number:
            self._serial_number = read_config('serial_number')
        return self._serial_number
