
#################################################
# HolAdo (Holistic Automation do)
#
# (C) Copyright 2021-2025 by Eric Klumpp
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

# The Software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software.
#################################################

import logging

from holado_core.common.exceptions.functional_exception import FunctionalException
from holado_resource.resource.persisted_data_manager import PersistedDataManager

logger = logging.getLogger(__name__)


class PersistedKeyValueManager(PersistedDataManager):
    def __init__(self, data_name="entry", table_name="key_value", db_name="default", do_audit=False):
        super().__init__(data_name=data_name, table_name=table_name,
                         table_sql_create=self._get_default_table_sql_create(table_name), 
                         unique_indexes_column_names=self._get_default_table_unique_indexes(),
                         db_name=db_name,
                         do_audit=do_audit)

    def initialize(self, resource_manager):
        super().initialize(resource_manager)

    def _get_default_table_sql_create(self, table_name):
        return f"""CREATE TABLE {table_name} (
                id INTEGER PRIMARY KEY,
                key text NOT NULL,
                value text NOT NULL
            )"""

    def _get_default_table_unique_indexes(self):
        return [('key',)]

    def set_value(self, key, value):
        """Add a key/value entry.
        @param key: Key
        @param value: Value
        """
        filter_data = {'key': key}
        data = {'value':value}
        self.update_or_add_persisted_data(persisted_filter_data=filter_data, data=data)

    def has_value(self, key):
        return self.has_persisted_data(filter_data={'key': key})

    def get_value(self, key):
        res = self.get_persisted_data(filter_data={'key': key})
        if res is None:
            raise FunctionalException(f"Key '{key}' not found.")
        return res['value']


    
