# encoding=utf-8


__author__ = "Roland Trouville"
__copyright__ = "Copyright 2015+, Consortium MonPaGe"
__license__ = "Creative Commons 4.0 By-Nc-Sa"
__maintainer__ = "Roland Trouville"
__email__ = "contact.monpage@gmail.com"
__status__ = "Production"

import logging
import os

from PySide6.QtCore import QDir

from tools.csv_manager import CSVManager

logger = logging.getLogger(__name__)


class PreferencesTools(object):
	"""
	A static utility class for managing user preferences stored in a CSV file.

	PreferencesTools allows for storing, retrieving, and persisting user-specific
	key-value configuration pairs, such as directory paths or other settings that
	need to persist between sessions.

	Preferences are saved to and loaded from the `preferences_config.csv` file,
	using tab-delimited format.

	Responsibilities:
	- Load preferences from a CSV file into memory.
	- Save in-memory preferences back to the CSV.
	- Get or set specific preference values by key.
	- Handle preferences related to directory paths.

	Attributes:
	    values (dict): A dictionary storing the loaded preferences in memory.
	"""

	values = {}

	@staticmethod
	def load_preferences_config():
		"""
		Load preferences from a tab-separated CSV file named 'preferences_config.csv'.

		Reads key-value pairs from the file and populates the PreferencesTools.values dictionary.
		Logs errors if the file is not found.

		Returns:
			bool: True if preferences loaded successfully, False otherwise.
		"""
		logger.info("Loading preferences")

		PreferencesTools.values = {}
		if not os.path.isfile("preferences_config.csv"):
			logger.error("File preferences_config.csv not found")
			return False

		logger.info("Reading preferences_config.csv")
		values = CSVManager.read_file("preferences_config.csv", "\t", -1)
		for val in values:
			logger.info(f"Loaded preference: {val[0]} = {val[1]}")
			PreferencesTools.values[val[0]] = val[1]
		return True

	@staticmethod
	def save_preferences_config():
		"""
		Save current preferences stored in PreferencesTools.values to 'preferences_config.csv'.

		Skips the key 'default' when saving.
		Uses tab as the delimiter and overwrites the file.
		"""
		logger.info("Saving preferences")
		save = []
		for key, value in PreferencesTools.values.items():
			if key != "default":
				save.append([key, value])

		logger.info("Writing preferences_config.csv")
		CSVManager.write_file("preferences_config.csv", "\t", save, "w+")
		logger.info("Writing file : preferences_config.csv")

	@staticmethod
	def get_preference_value(key):
		"""
		Retrieve the value of a preference given its key.

		Args:
			key (str): The preference key.

		Returns:
			str or None: The value associated with the key, or None if the key does not exist.
		"""
		try:
			return PreferencesTools.values[key]
		except KeyError:
			return None

	@staticmethod
	def set_preference_value(key, value):
		"""
		Set or update the value of a preference key.

		Args:
			key (str): The preference key.
			value (str): The value to set.
		"""
		PreferencesTools.values[key] = value

	@staticmethod
	def has_preference_value(key):
		"""
		Check if a preference key exists in the stored preferences.

		Args:
			key (str): The preference key.

		Returns:
			bool: True if the key exists and is not None, False otherwise.
		"""
		if key is None:
			return False
		return key in PreferencesTools.values

	@staticmethod
	def get_preference_directory_path(key):
		"""
		Get a directory path preference for the given key.

		If the stored path exists and is a directory, returns it as a native OS path.
		Otherwise, returns the current working directory path.

		Args:
			key (str): The preference key.

		Returns:
			str: The directory path for the preference key or current directory if not set or invalid.
		"""
		path = QDir.toNativeSeparators(QDir.currentPath())
		last_path = PreferencesTools.get_preference_value(key)
		if last_path is not None:
			last_path = QDir.toNativeSeparators(last_path)
			if os.path.isdir(last_path):
				path = last_path
		return path

	@staticmethod
	def set_preference_directory_path_from_filename(key, filename):
		"""
		Set a directory path preference derived from the directory containing the given filename.

		Extracts the directory path from the filename and sets it as the value for the given key.

		Args:
			key (str): The preference key.
			filename (str): The full filename from which to extract the directory path.
		"""
		tmp = filename.strip().split(os.path.sep)
		del tmp[-1]
		path = os.path.sep.join(tmp)
		PreferencesTools.set_preference_value(key, path)
