import logging
from typing import List, Set, Tuple
from .backend._Backend import _Backend

LOGGER = logging.getLogger(__name__)

class Database:
    def __init__(self, backend : _Backend):
        if not isinstance(backend, _Backend):
            str_class_path = '{}.{}'.format(_Backend.__module__, _Backend.__name__)
            raise AttributeError('backend must inherit from {}'.format(str_class_path))
        self._backend = backend

    @property
    def backend(self) -> _Backend: return self._backend

    def clear_all(self, keep_keys : Set[str] = set()) -> None:
        for key in self._backend.keys():
            if key in keep_keys: continue
            self._backend.delete(key)

    def dump(self) -> List[Tuple[str, str, str]]:
        entries = self._backend.dump()
        entries.sort()
        _entries = []
        for str_key, str_type, value in entries:
            if isinstance(value, list):
                str_value = ', '.join(map("'{:s}'".format, sorted(list(value))))
                str_value = '[' + str_value + ']'
            elif isinstance(value, set):
                str_value = ', '.join(map("'{:s}'".format, sorted(list(value))))
                str_value = '{' + str_value + '}'
            elif isinstance(value, dict):
                sorted_keys = sorted(value.keys())
                str_value = ', '.join(["'{}': '{}'".format(key, value[key]) for key in sorted_keys])
                str_value = '{' + str_value + '}'
            _entries.append((str_type, str_key, str_value))
        return _entries
