from textual.app import App
from pathlib import Path
import os
import configparser
from typing import Any


class ConfigHandler:
	def __init__(self, app: App):
		self.app: App = app
		self.config: configparser.ConfigParser = configparser.ConfigParser()
		
		self.plugin_defined_settings = {}
		self.config_dir: str = self.ensure_hidden_config_dir()
		self.load_settings()
	
	def ensure_hidden_config_dir(self):
		config_dir = Path.home() / ".termdaw"
		config_dir.mkdir(parents=True, exist_ok=True)

		return config_dir

	def get(self, section: str, option: str) -> str:
		if not self.config.has_section(section):
			self.config.add_section(section)
		if not self.config.has_option(section, option):
			self.set(section, option, "0")
			return "0"

		return self.config.get(section, option, fallback=None)
	
	def set(self, section: str, option: str, new_value: str):
		if not self.config.has_section(section):
			self.config.add_section(section)
		self.config.set(section, option, new_value)

		self.write_settings()

	def apply_settings(self):
		self.app.theme = self.get("appearance", "colour_theme")

	def write_settings(self):
		with open(self.config_dir / "config.ini", "w") as configfile:
			self.config.write(configfile)

	def load_settings(self):
		if os.path.isfile(self.config_dir / "config.ini"):
			self.config.read(self.config_dir / "config.ini")
			return

		self.config["config"] = {
			"version": "1"
		}
		self.config["appearance"] = {
			"colour_theme": "textual-dark"
		}
		self.config["audio"] = {
			"output_device": "None",
			"input_device": "None"
		}

		with open(self.config_dir / "config.ini", "w") as configfile:
			self.config.write(configfile)