# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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
