import abc
import json

from .core import Group, Primitive


class VarsEditor(abc.ABC):

    @abc.abstractmethod
    def write(self, key: str, value: str): ...

    @abc.abstractmethod
    def list_vars(self) -> list[str]: ...

    @abc.abstractmethod
    def read(self, key: str) -> str: ...


class ConfigEditor:
    def __init__(self, editor: VarsEditor):
        self._editor = editor

    def list(self) -> list[str]:
        return self._editor.list_vars()

    def get(self, key: str) -> Group | Primitive:
        var = self._editor.read(key)
        value = json.loads(var)
        if type(value) is dict:
            return Group(value)
        return value

    def set(self, key: str, value: Group | Primitive):
        self._editor.write(key, json.dumps(value))
