from lib.helpers import get_resource
from PyQt5.QtCore import QObject, Qt, QUrl
from PyQt5.QtQuickWidgets import QQuickWidget

# TODO: https://www.pythonguis.com/tutorials/qml-qtquick-python-application/


class Qml_Widget(QQuickWidget):
    def __init__(self, background=None):
        super().__init__()
        self.setAttribute(Qt.WA_DeleteOnClose)
        # self.setAttribute(Qt.WA_TranslucentBackground)
        if background is None:
            self.setClearColor(Qt.transparent)
            self.setAttribute(Qt.WA_AlwaysStackOnTop)
        else:
            self.setClearColor(background)
        me = self.__class__.__name__
        u = get_resource("ui/{0}/{0}.qml".format(me.lower()))
        self.setSource(QUrl(u))
        # self.qml_item = self.rootObject().findChild(QObject, me)
        self.qml_item = self.rootObject()
        # self.setResizeMode(self.SizeViewToRootObject)
        # self.setResizeMode(self.SizeRootObjectToView)
        # print(self.dump(self.get_child(self.qml_item, "gauge")), flush=True)

    # def dump(self, object=None):
    #     if object is None:
    #         object = self.qml_item
    #     mo = object.metaObject()
    #     d = {}
    #     for i in range(mo.propertyCount()):
    #         mp = mo.property(i)
    #         try:
    #             d[mp.name()] = mp.read(object)
    #         except TypeError:
    #             d[mp.name()] = None
    #     return d

    def get_child(self, item=None, address=0):
        if item is None:
            item = self.qml_item

        def _get_child(item, address=0):
            if address is None:
                return item
            elif type(address) is str:
                return item.findChild(QObject, address)
            elif type(address) is int:
                children = item.children()
                if address < len(children):
                    return children[address]
                else:
                    raise AttributeError("{!r}".format(address))

        try:
            if type(address) is list:
                for a in address:
                    item = _get_child(item, a)
            else:
                item = _get_child(item, address)
            return item
        except AttributeError as e:
            raise AttributeError("qml child item not found: {} ({!r})".format(str(e), address))

    def set(self, property, value, child=None):
        item = self.get_child(self.qml_item, child)
        item.setProperty(property, value)

    def get(self, property, child=None):
        item = self.get_child(self.qml_item, child)
        return item.property(property)
