from ..models.config import Config
from peewee import DoesNotExist
import logging

logger = logging.getLogger("median.config")


class RawConfig:
    poste = "TOUS"
    cle = "cfg"

    def __init__(self, c_poste=None, c_cle=None):
        self.poste = c_poste or "TOUS"
        self.cle = c_cle or "cfg"

    def _process_config_value(self, res):
        """Process and convert config value based on type"""
        if res.type_value == "N" and res.type_champ == "num":
            res.value = int(res.value)
        elif res.type_value == "N" and res.type_champ == "bool":
            res.value = int(res.value) and True or False
        return res

    def read(self, param=""):
        """read a Raw value"""
        result = None
        try:
            res = Config.get(poste=self.poste, cle=self.cle, propriete=param)
            # import pdb; pdb.set_trace()
            result = self._process_config_value(res)
            logger.debug('Poste "%s" lecture paramètre "%s"' % (self.poste, param))
        except DoesNotExist:
            logger.debug('Poste "%s" paramètre "%s" non trouvé' % (self.poste, param))
            # Retry with "TOUS" as fallback if current poste is not "TOUS"
            if self.poste != "TOUS":
                try:
                    res = Config.get(poste="TOUS", cle=self.cle, propriete=param)
                    result = self._process_config_value(res)
                    logger.debug('Poste "TOUS" fallback lecture paramètre "%s" réussie' % param)
                except DoesNotExist:
                    logger.debug('Poste "TOUS" fallback paramètre "%s" non trouvé' % param)

        return result

    def write(self, param="", value=None):
        """write a Raw value"""
        try:
            res = Config.get(poste=self.poste, cle=self.cle, propriete=param)
            if type(value) is bool:
                res.value = str(value and 1 or 0)
            elif type(value) is int:
                res.value = str(value)
            else:
                res.value = value
            res.save()
            logger.debug('Poste "%s" mise à jour paramètre "%s"' % (self.poste, param))
        except DoesNotExist:
            res = Config(poste=self.poste, cle=self.cle)
            res.propriete = param
            if type(value) is bool:
                res.value = str(value and 1 or 0)
                res.type_value = "N"
                res.type_champ = "bool"
            elif type(value) is int:
                res.value = str(value)
                res.type_value = "N"
                res.type_champ = "num"
            else:
                res.type_value = "C"
                res.type_champ = "reg"
                res.value = value
            res.save()
            logger.debug('Poste "%s" création paramètre "%s"' % (self.poste, param))

        if isinstance(value, (int, bool)):
            res.value = value

        return res

    def delete(self, param=""):
        try:
            res = Config.get(poste=self.poste, cle=self.cle, propriete=param)
            res.delete_instance()
            logger.debug('Poste "%s" suppression paramètre "%s"' % (self.poste, param))
        except DoesNotExist:
            pass
