import subprocess
import json
import logging

from os import makedirs
from os.path import dirname, isdir

from owltail import settings
from owltail.api_handler import APIHandler

logger = logging.getLogger(__name__)


class SerialNumberReader:
    def get_serial_number(self):
        output = subprocess.check_output(
            [settings.SERIAL_NUMBER_READ_COMMAND], shell=True
        )
        return output.decode("utf-8").split(':', 2)[-1].strip()


class Configurer:
    def __init__(
        self,
        api_handler=APIHandler(),
        serial_number_reader=SerialNumberReader(),
    ):
        self.api_handler = api_handler
        self.serial_number_reader = serial_number_reader

    def start(self):
        logger.info('Starting configuration script…')
        serial_number = self.serial_number_reader.get_serial_number()
        logger.debug('Serial number = {}'.format(serial_number))
        json_conf = self.api_handler.get_configuration(serial_number)
        logger.debug('API Response = {}'.format(json_conf))
        dirpath = dirname(settings.CONFIG_FILE_PATH)
        if not isdir(dirpath):
            makedirs(dirpath)
        if json_conf:
            with open(settings.CONFIG_FILE_PATH, 'w') as conf_file:
                conf_file.write(json.dumps(json_conf))
        logger.info('Finished configuration script')
