import os
import json
import logging

from PySide2.QtWidgets import QMessageBox

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)


class ProtocolDescription(object):
    def __init__(self):

        path_list = list()
        path_list.append(".")
        path_list.append("..")
        script_path = os.path.dirname(os.path.realpath(__file__))
        path_list.append(os.path.join(script_path, ".."))
        path_list.append(os.path.join(script_path, "..\\.."))

        self.proto_file = None
        for path in path_list:
            file_path = os.path.join(os.path.abspath(path), "protocol_definition.json")
            if not os.path.isfile(file_path):
                logger.info(f"file '{file_path}' not found")
            else:
                self.proto_file = file_path
                logger.info(f"using file '{file_path}'")
                break

        with open(os.path.abspath(self.proto_file), 'r', encoding="utf-8") as f:
            try:
                j = json.load(f)
            except ValueError:
                return
            self.json = j
            self.items = j.keys()
        dev_set = j["device"]
        dev_versions = dict(dev_set)
        for dev in dev_set:
            ver_set = dev_set[dev]["version"]
            dev_versions[dev] = list()
            for ver in ver_set:
                dev_versions[dev].append(ver)

        self.devices_versions = dev_versions


class DevType(ProtocolDescription):
    def __init__(self, sel_dev_set, sel_dev_menu, sel_ver_set, sel_ver_menu):
        ProtocolDescription.__init__(self)
        self.sel_dev_set, self.sel_dev_menu = sel_dev_set, sel_dev_menu
        self.sel_ver_set, self.sel_ver_menu = sel_ver_set, sel_ver_menu
        self.refresh_dev()

    def refresh_dev(self):
        # refresh devices-menu
        self.sel_dev_set = self.devices_versions.keys()
        self.sel_dev_menu.clear()
        self.set_dev()

        # clear versions-menu
        self.sel_ver_menu.clear()

    def set_dev(self):
        self.sel_ver_menu.clear()
        self.sel_dev_menu.addItems(list(self.sel_dev_set))


class CmdVersion(DevType):
    def __init__(self, sel_dev_set, sel_dev_menu, sel_ver_set, sel_ver_menu):
        DevType.__init__(self, sel_dev_set, sel_dev_menu, sel_ver_set, sel_ver_menu)
        self.sel_dev_set, self.sel_dev_menu = sel_dev_set, sel_dev_menu
        self.sel_ver_set, self.sel_ver_menu = sel_ver_set, sel_ver_menu
        self.proto = None
        self.refresh_ver()

    def refresh_ver(self):
        sel_dev = self.sel_dev_menu.currentText()

        if sel_dev in self.devices_versions:
            self.sel_ver_set = self.devices_versions[sel_dev]

        self.sel_ver_menu.clear()
        self.set_ver()

    def set_ver(self):
        self.sel_ver_menu.addItems(self.sel_ver_set)

    def get_selected_proto(self):
        sel_dev = self.sel_dev_menu.currentText()
        sel_ver = self.sel_ver_menu.currentText()

        # if sel_ver == "fallback":
        #     msg_box = QMessageBox()
        #     button_reply = msg_box.question(self, "Hinweis", "Gerät und / oder Version nicht ausgewählt. \nFortfahren?",
        #                                        QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        #     if button_reply == False:
        #         return None

        if sel_dev in self.json["device"] and sel_ver in self.json["device"][sel_dev]["version"]:
            self.proto = self.json["device"][sel_dev]["version"][sel_ver]
        else:
            self.proto = self.json["device"]["fallback"]["version"]["fallback"]
        return self.proto
