music-kraken-core/src/music_kraken/objects/collection.py

222 lines
7.4 KiB
Python
Raw Normal View History

2023-08-30 19:14:03 +00:00
from typing import List, Iterable, Dict, TypeVar, Generic, Iterator
2023-03-09 17:35:56 +00:00
from collections import defaultdict
2023-03-24 14:58:21 +00:00
from dataclasses import dataclass
2023-02-07 18:26:14 +00:00
2023-03-09 17:19:49 +00:00
from .parents import DatabaseObject
2023-10-12 17:24:35 +00:00
from ..utils.hooks import HookEventTypes, Hooks, Event
class CollectionHooks(HookEventTypes):
APPEND_NEW = "append_new"
2023-02-07 18:26:14 +00:00
2023-02-23 22:52:41 +00:00
2023-08-28 18:59:19 +00:00
T = TypeVar('T', bound=DatabaseObject)
2023-03-24 14:58:21 +00:00
@dataclass
class AppendResult:
was_in_collection: bool
current_element: DatabaseObject
2023-04-03 14:23:30 +00:00
was_the_same: bool
2023-03-24 14:58:21 +00:00
2023-08-28 18:59:19 +00:00
class Collection(Generic[T]):
2023-02-07 18:26:14 +00:00
"""
This a class for the iterables
2023-02-07 18:26:14 +00:00
like tracklist or discography
"""
2023-08-28 18:59:19 +00:00
_data: List[T]
2023-02-23 22:52:41 +00:00
2023-02-07 18:26:14 +00:00
_by_url: dict
_by_attribute: dict
2023-08-28 18:59:19 +00:00
def __init__(self, data: List[T] = None, element_type=None, *args, **kwargs) -> None:
2023-03-09 17:19:49 +00:00
# Attribute needs to point to
self.element_type = element_type
2023-03-24 14:58:21 +00:00
2023-08-28 18:59:19 +00:00
self._data: List[T] = list()
2023-03-24 14:58:21 +00:00
2023-02-07 18:26:14 +00:00
"""
2023-03-09 17:19:49 +00:00
example of attribute_to_object_map
the song objects are references pointing to objects
in _data
```python
{
'id': {323: song_1, 563: song_2, 666: song_3},
'url': {'www.song_2.com': song_2}
}
```
2023-02-07 18:26:14 +00:00
"""
2023-08-28 18:59:19 +00:00
self._attribute_to_object_map: Dict[str, Dict[object, T]] = defaultdict(dict)
2023-03-14 10:03:54 +00:00
self._used_ids: set = set()
2023-03-24 14:58:21 +00:00
2023-10-12 17:24:35 +00:00
self.hooks: Hooks = Hooks(self)
2023-03-10 09:13:35 +00:00
if data is not None:
self.extend(data, merge_on_conflict=True)
2023-02-07 18:26:14 +00:00
2023-02-23 22:52:41 +00:00
def sort(self, reverse: bool = False, **kwargs):
self._data.sort(reverse=reverse, **kwargs)
2023-08-28 18:59:19 +00:00
def map_element(self, element: T):
2023-03-09 17:35:56 +00:00
for name, value in element.indexing_values:
2023-03-10 17:38:32 +00:00
if value is None:
continue
2023-03-09 17:35:56 +00:00
self._attribute_to_object_map[name][value] = element
2023-03-24 14:58:21 +00:00
2023-03-14 10:03:54 +00:00
self._used_ids.add(element.id)
2023-03-24 14:58:21 +00:00
2023-08-28 18:59:19 +00:00
def unmap_element(self, element: T):
2023-03-22 11:58:11 +00:00
for name, value in element.indexing_values:
if value is None:
continue
2023-03-24 14:58:21 +00:00
2023-03-22 11:58:11 +00:00
if value in self._attribute_to_object_map[name]:
if element is self._attribute_to_object_map[name][value]:
try:
self._attribute_to_object_map[name].pop(value)
except KeyError:
pass
2023-02-07 18:26:14 +00:00
2023-08-28 18:59:19 +00:00
def append(self, element: T, merge_on_conflict: bool = True,
2023-10-12 17:24:35 +00:00
merge_into_existing: bool = True, no_hook: bool = False) -> AppendResult:
2023-03-09 21:14:39 +00:00
"""
:param element:
:param merge_on_conflict:
2023-03-22 11:58:11 +00:00
:param merge_into_existing:
:return did_not_exist:
2023-03-09 21:14:39 +00:00
"""
2023-09-13 14:01:01 +00:00
if element is None:
return AppendResult(False, None, False)
2023-03-09 21:14:39 +00:00
2023-10-12 17:24:35 +00:00
for existing_element in self._data:
if element is existing_element:
return AppendResult(False, None, False)
2023-03-09 21:14:39 +00:00
# if the element type has been defined in the initializer it checks if the type matches
2023-03-10 09:13:35 +00:00
if self.element_type is not None and not isinstance(element, self.element_type):
2023-02-08 12:16:48 +00:00
raise TypeError(f"{type(element)} is not the set type {self.element_type}")
2023-04-03 14:23:30 +00:00
# return if the same instance of the object is in the list
for existing in self._data:
if element is existing:
return AppendResult(True, element, True)
2023-02-08 12:16:48 +00:00
2023-03-09 17:35:56 +00:00
for name, value in element.indexing_values:
if value in self._attribute_to_object_map[name]:
2023-03-21 11:46:32 +00:00
existing_object = self._attribute_to_object_map[name][value]
2023-03-24 14:58:21 +00:00
2023-03-24 13:28:19 +00:00
if not merge_on_conflict:
2023-04-03 14:23:30 +00:00
return AppendResult(True, existing_object, False)
2023-03-24 14:58:21 +00:00
2023-03-24 13:28:19 +00:00
# if the object does already exist
2023-05-24 23:27:05 +00:00
# thus merging and don't add it afterward
2023-03-24 13:28:19 +00:00
if merge_into_existing:
existing_object.merge(element)
# in case any relevant data has been added (e.g. it remaps the old object)
self.map_element(existing_object)
2023-04-03 14:23:30 +00:00
return AppendResult(True, existing_object, False)
2023-03-24 14:58:21 +00:00
2023-03-24 13:28:19 +00:00
element.merge(existing_object)
2023-03-24 14:58:21 +00:00
2023-03-24 13:28:19 +00:00
exists_at = self._data.index(existing_object)
self._data[exists_at] = element
2023-03-24 14:58:21 +00:00
2023-03-24 13:28:19 +00:00
self.unmap_element(existing_object)
self.map_element(element)
2023-04-03 14:23:30 +00:00
return AppendResult(True, existing_object, False)
2023-03-02 15:23:02 +00:00
2023-10-12 17:24:35 +00:00
if not no_hook:
self.hooks.trigger_event(CollectionHooks.APPEND_NEW, new_object=element)
2023-02-07 18:26:14 +00:00
self._data.append(element)
self.map_element(element)
2023-02-08 12:16:48 +00:00
2023-04-03 14:23:30 +00:00
return AppendResult(False, element, False)
2023-03-24 14:58:21 +00:00
2023-08-28 18:59:19 +00:00
def extend(self, element_list: Iterable[T], merge_on_conflict: bool = True,
2023-10-12 17:24:35 +00:00
merge_into_existing: bool = True, no_hook: bool = False):
if element_list is None:
return
if len(element_list) <= 0:
return
if element_list is self:
return
2023-03-03 11:32:08 +00:00
for element in element_list:
2023-10-12 17:24:35 +00:00
self.append(element, merge_on_conflict=merge_on_conflict, merge_into_existing=merge_into_existing, no_hook=no_hook)
def sync_collection(self, collection_attribute: str):
def on_append(event: Event, new_object: T, *args, **kwargs):
new_collection = new_object.__getattribute__(collection_attribute)
if self is new_collection:
return
self.extend(new_object.__getattribute__(collection_attribute), no_hook=True)
new_object.__setattr__(collection_attribute, self)
self.hooks.add_event_listener(CollectionHooks.APPEND_NEW, on_append)
def sync_main_collection(self, main_collection: "Collection", collection_attribute: str):
def on_append(event: Event, new_object: T, *args, **kwargs):
new_collection = new_object.__getattribute__(collection_attribute)
if main_collection is new_collection:
return
main_collection.extend(new_object.__getattribute__(collection_attribute), no_hook=True)
new_object.__setattr__(collection_attribute, main_collection)
self.hooks.add_event_listener(CollectionHooks.APPEND_NEW, on_append)
"""
def on_append(event: Event, new_object: T, *args, **kwargs):
new_collection: Collection = new_object.__getattribute__(collection_attribute)
if self is new_collection:
return
self.extend(new_collection.shallow_list, no_hook=False)
new_object.__setattr__(collection_attribute, self)
self.hooks.add_event_listener(CollectionHooks.APPEND_NEW, on_append)
"""
2023-03-03 11:32:08 +00:00
2023-08-30 19:14:03 +00:00
def __iter__(self) -> Iterator[T]:
2023-10-12 17:24:35 +00:00
for element in self._data:
2023-02-08 12:16:48 +00:00
yield element
def __str__(self) -> str:
2023-03-02 15:23:02 +00:00
return "\n".join([f"{str(j).zfill(2)}: {i.__repr__()}" for j, i in enumerate(self._data)])
2023-02-08 16:14:51 +00:00
def __len__(self) -> int:
return len(self._data)
2023-08-30 19:14:03 +00:00
def __getitem__(self, key) -> T:
2023-03-24 14:58:21 +00:00
if type(key) != int:
2023-02-23 22:52:41 +00:00
return ValueError("key needs to be an integer")
2023-03-24 14:58:21 +00:00
return self._data[key]
2023-08-28 18:59:19 +00:00
def __setitem__(self, key, value: T):
2023-03-24 14:58:21 +00:00
if type(key) != int:
return ValueError("key needs to be an integer")
old_item = self._data[key]
self.unmap_element(old_item)
self.map_element(value)
self._data[key] = value
2023-02-23 22:52:41 +00:00
2023-03-10 08:09:35 +00:00
@property
2023-08-28 18:59:19 +00:00
def shallow_list(self) -> List[T]:
2023-02-08 16:14:51 +00:00
"""
returns a shallow copy of the data list
"""
return self._data.copy()
2023-03-30 12:39:28 +00:00
@property
def empty(self) -> bool:
return len(self._data) == 0
def clear(self):
self.__init__(element_type=self.element_type)