from dataclasses import dataclass
from typing import Any, Self, override

from archinstall.lib.locale.utils import get_kb_layout
from archinstall.lib.models.config import SubConfig
from archinstall.lib.translationhandler import tr


@dataclass
class LocaleConfiguration(SubConfig):
	kb_layout: str
	sys_lang: str
	sys_enc: str
	# this is the default used in ISO other option for hdpi screens TER16x32
	# can be checked using
	# zgrep "CONFIG_FONT" /proc/config.gz
	# https://wiki.archlinux.org/title/Linux_console#Font
	console_font: str = 'default8x16'

	@classmethod
	def default(cls) -> Self:
		layout = get_kb_layout()
		if layout == '':
			layout = 'us'
		return cls(layout, 'en_US.UTF-8', 'UTF-8')

	@override
	def json(self) -> dict[str, str]:
		return {
			'kb_layout': self.kb_layout,
			'sys_lang': self.sys_lang,
			'sys_enc': self.sys_enc,
			'console_font': self.console_font,
		}

	@override
	def summary(self) -> list[str]:
		return [
			tr('Keyboard layout "{}"').format(self.kb_layout),
			tr('Locale language "{}"').format(self.sys_lang),
			tr('Locale encoding "{}"').format(self.sys_enc),
			tr('Console font "{}"').format(self.console_font),
		]

	def preview(self) -> str:
		output = '{}: {}\n'.format(tr('Keyboard layout'), self.kb_layout)
		output += '{}: {}\n'.format(tr('Locale language'), self.sys_lang)
		output += '{}: {}\n'.format(tr('Locale encoding'), self.sys_enc)
		output += '{}: {}'.format(tr('Console font'), self.console_font)
		return output

	def _load_config(self, args: dict[str, str]) -> None:
		if 'sys_lang' in args:
			self.sys_lang = args['sys_lang']
		if 'sys_enc' in args:
			self.sys_enc = args['sys_enc']
		if 'kb_layout' in args:
			self.kb_layout = args['kb_layout']
		if 'console_font' in args:
			self.console_font = args['console_font']

	@classmethod
	def parse_arg(cls, args: dict[str, Any]) -> Self:
		default = cls.default()

		if 'locale_config' in args:
			default._load_config(args['locale_config'])
		else:
			default._load_config(args)

		return default
