import sys

from PySide2 import QtWidgets as qtw

from config_dialog import Ui_ConfigDialog


class Config(qtw.QDialog):
    def __init__(self, parent):
        super(Config, self).__init__(parent)
        self.parent = parent
        self.ui = Ui_ConfigDialog()
        self.ui.setupUi(self)
        lines = open('locales/languages.lst', encoding='utf8').readlines()
        self.lang_codes = []
        cur_lang = self.parent.settings.value('language', 'en_US', type=str)
        cur_index = 0
        for index, line in enumerate(lines):
            if line.count(':') != 1:
                qtw.QMessageBox.critical(self, parent.tr('Error'), parent.tr('Error in languages.lst file format\nPlease see the READ.ME file in locales folder'))
                sys.exit(1)
            parts = line.strip().split(":")
            self.lang_codes.append(parts[0])
            self.ui.languageComboBox.addItem(parts[1])
            if cur_lang == parts[0]:
                cur_index = index
        self.ui.languageComboBox.setCurrentIndex(cur_index)
        if len(lines) < 2:
            self.ui.languageComboBox.setVisible(False)
            self.ui.langLabel.setVisible(False)
        self.ui.randomEnginComboBox.addItem('Random')
        self.ui.randomEnginComboBox.addItem('Secret')
        cur_engine = self.parent.settings.value('random_engine', 'random', type=str)
        if cur_engine == 'random':
            self.ui.randomEnginComboBox.setCurrentIndex(0)
        else:
            self.ui.randomEnginComboBox.setCurrentIndex(1)
        self.ui.savePushButton.clicked.connect(self.on_save_config)

    def on_save_config(self):
        lang_index = self.ui.languageComboBox.currentIndex()
        self.parent.settings.setValue('language', self.lang_codes[lang_index])
        random_index = self.ui.randomEnginComboBox.currentIndex()
        self.parent.settings.setValue('random_engine', ('random', 'secret')[random_index])
        self.close()