from __future__ import annotations
from typing import List
from ..backend._Backend import _Backend
from ._Object import _Object
from .Tools import format_key

class Collection:
    def __init__(self, parent : _Object, key_pattern : str):
        if not issubclass(parent, _Object):
            str_class_path = '{}.{}'.format(_Object.__module__, _Object.__name__)
            raise AttributeError('parent must inherit from {}'.format(str_class_path))
        if (not isinstance(key_pattern, str)) or (len(key_pattern) == 0):
            raise AttributeError('key_pattern must be a non-empty instance of str')

        self._parent = parent
        self._backend : _Backend = self._parent.backend
        self._key_list = format_key(key_pattern, self._parent, container_name='_list')
        self._key_set = format_key(key_pattern, self._parent, container_name='_set')

    def add(self, object_uuid : str) -> None:
        if self._backend.set_has(self._key_set, object_uuid): return
        self._backend.set_add(self._key_set, object_uuid)
        self._backend.list_push_last(self._key_list, object_uuid)

    def get(self) -> List[str]:
        return self._backend.list_get_all(self._key_list)

    def contains(self, object_uuid : str) -> bool:
        return self._backend.set_has(self._key_set, object_uuid)

    def clear(self) -> None:
        self._backend.delete(self._key_set)
        self._backend.delete(self._key_list)

    def delete(self, object_uuid : str) -> None:
        if not self._backend.set_has(self._key_set, object_uuid): return
        self._backend.set_remove(self._key_set, object_uuid)
        self._backend.list_remove_first_occurrence(self._key_list, object_uuid)
