import logging
from handler_library.handler import GenericDataHandler
from PySide2.QtCore import Signal, Slot
from PySide2.QtGui import QFont
import json
import os


class TextHandler(GenericDataHandler):
    UpdateText = Signal(dict)

    def __init__(self, localisation_files: list, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.__localisation_files: list = []
        self.__localisation_index = 0

        for filepath in localisation_files:
            if os.path.isfile(filepath):
                self.__localisation_files.append(filepath)
            else:
                raise FileNotFoundError(
                    "Could not locate localisation config file %s", filepath
                )

        self.set_db(
            {
                "label_text_font": QFont("Sans Serif", 20),
                "measurement_text_font": QFont("Sans Serif", 40),
            }
        )

    def next_config(self) -> int:
        """
        Iterate the localisation to the next option in the __localisation_files list.
        """
        index = self.__localisation_index
        index += 1
        if index > len(self.__localisation_files):
            index = 0
        self.set_localisation(index)
        return 0

    @Slot()
    def set_localisation(self, index: int) -> int:
        """
        Update the current localisation index to the specified value and load the
        corresponding file.
        """
        if index > len(self.__localisation_files):
            raise IndexError(
                "Could not index list %s with index %s",
                (self.__localisation_files, index),
            )

        self.__localisation_index = index
        with open(self.__localisation_files[self.__localisation_index]) as infile:
            self.set_db(json.load(infile))
        return 0

    def on_data_set(self) -> int:
        """
        When the database is updated, emit a signal containing the current text dictionary
        """
        self.UpdateText.emit(self.get_db())
        return 0
