import json
from pathlib import Path

DEFAULT_PATH = Path.home() / ".config" / "brewpi" / "gui.json"


class UserConfig:
	"""Small persisted key/value store for GUI preferences that should
	survive across restarts (e.g. the last directory used for a file
	dialog) - local user state, not version-controlled config."""

	def __init__(self, path=DEFAULT_PATH):
		self.path = path
		self.data = {}
		if self.path.exists():
			try:
				self.data = json.loads(self.path.read_text())
			except (json.JSONDecodeError, OSError):
				self.data = {}

	def get(self, key, default=None):
		return self.data.get(key, default)

	def set(self, key, value):
		self.data[key] = value
		self.path.parent.mkdir(parents=True, exist_ok=True)
		self.path.write_text(json.dumps(self.data, indent='\t'))
