# 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.

# InMemeory Database Backend
# --------------------------
# - Concurrency is limited to 1 operation at a time
# - All operations are strictly sequential by means of locks
# - WARNING: DESIGNED AND BUILT FOR UNIT TESTING AND INTEGRATION TESTING PURPOSES ONLY !!!
#            USE ANOTHER BACKEND IN PRODUCTION ENVIRONMENTS.

import copy, logging, threading, uuid
from typing import Any, Dict, List, Optional, Set, Tuple, Union
from .._Backend import _Backend
from ..Tools import key_to_str
from .Tools import get_dict, get_list, get_or_create_dict, get_or_create_list, get_or_create_set, get_set

LOGGER = logging.getLogger(__name__)

class InMemoryBackend(_Backend):
    def __init__(self, **settings): # pylint: disable=super-init-not-called
        self._lock = threading.Lock()
        self._keys : Dict[str, Union[Set[str], List[str], Dict[str, str], str]]= {} # key => set/list/dict/string

    def lock(self, keys : List[List[str]], owner_key : Optional[str] = None) -> Tuple[bool, str]:
        # InMemoryBackend uses a database where all operations are atomic. Locks are implemented by assigning the lock
        # owner key into a string variable. If the field is empty and enables to 
        owner_key = str(uuid.uuid4()) if owner_key is None else owner_key
        str_keys = {key_to_str(key) for key in keys}
        with self._lock:
            acquired_lock_keys : Dict[str, str] = {}
            for str_key in str_keys:
                if (str_key in self._keys) and (len(self._keys[str_key]) > 0) and (self._keys[str_key] != owner_key):
                    # lock already acquired, cannot acquire all locks atomically
                    for str_key_acquired in acquired_lock_keys:
                        if str_key_acquired not in self._keys: continue
                        del self._keys[str_key_acquired]
                    return False, None

                # lock available, temporarily acquire it; locks will be released if some of them for a requested
                # key is not available
                self._keys[str_key] = owner_key
                acquired_lock_keys[str_key] = owner_key
            return True, owner_key

    def unlock(self, keys : List[List[str]], owner_key : str) -> bool:
        str_keys = {key_to_str(key) for key in keys}
        with self._lock:
            for str_key in str_keys:
                if str_key not in self._keys: return False
                if self._keys[str_key] != owner_key: return False
            # Up to here, we own all the keys we want to release
            for str_key in str_keys:
                del self._keys[str_key]
            return True

    def keys(self) -> list:
        with self._lock:
            return copy.deepcopy(list(self._keys.keys()))

    def exists(self, key : List[str]) -> bool:
        str_key = key_to_str(key)
        with self._lock:
            return str_key in self._keys

    def delete(self, key : List[str]) -> bool:
        str_key = key_to_str(key)
        with self._lock:
            if str_key not in self._keys: return False
            del self._keys[str_key]
            return True

    def dict_get(self, key : List[str], fields : List[str] = []) -> Dict[str, str]:
        str_key = key_to_str(key)
        with self._lock:
            container = get_dict(self._keys, str_key)
            if container is None: return {}
            if len(fields) == 0: fields = container.keys()
            return copy.deepcopy({
                field_name : field_value for field_name,field_value in container.items() if field_name in fields
            })

    def dict_update(self, key : List[str], fields : Dict[str,str] = {}) -> None:
        str_key = key_to_str(key)
        with self._lock:
            container = get_or_create_dict(self._keys, str_key)
            container.update(fields)

    def dict_delete(self, key : List[str], fields : List[str] = []) -> None:
        str_key = key_to_str(key)
        with self._lock:
            if len(fields) == 0:
                if str_key not in self._keys: return False
                del self._keys[str_key]
            else:
                container = get_or_create_dict(self._keys, str_key)
                for field in list(fields): container.pop(field, None)
                if len(container) == 0: self._keys.pop(str_key)

    def list_get_all(self, key : List[str]) -> List[str]:
        str_key = key_to_str(key)
        with self._lock:
            container = get_list(self._keys, str_key)
            if container is None: return []
            return copy.deepcopy(container)

    def list_push_last(self, key : List[str], item : str) -> None:
        str_key = key_to_str(key)
        with self._lock:
            container = get_or_create_list(self._keys, str_key)
            container.append(item)

    def list_remove_first_occurrence(self, key : List[str], item: str) -> None:
        str_key = key_to_str(key)
        with self._lock:
            container = get_or_create_list(self._keys, str_key)
            container.remove(item)
            if len(container) == 0: self._keys.pop(str_key)

    def set_add(self, key : List[str], item : str) -> None:
        str_key = key_to_str(key)
        with self._lock:
            container = get_or_create_set(self._keys, str_key)
            container.add(item)

    def set_has(self, key : List[str], item : str) -> bool:
        str_key = key_to_str(key)
        with self._lock:
            container = get_or_create_set(self._keys, str_key)
            return item in container

    def set_get_all(self, key : List[str]) -> Set[str]:
        str_key = key_to_str(key)
        with self._lock:
            container = get_set(self._keys, str_key)
            if container is None: return {}
            return copy.deepcopy(container)

    def set_remove(self, key : List[str], item : str) -> None:
        str_key = key_to_str(key)
        with self._lock:
            container = get_or_create_set(self._keys, str_key)
            container.discard(item)
            if len(container) == 0: self._keys.pop(str_key)

    def dump(self) -> List[Tuple[str, str, Any]]:
        with self._lock:
            entries = []
            for str_key,key_value in self._keys.items():
                entries.append((str_key, type(key_value).__name__, key_value))
        return entries
