import weakref

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from ui.helpers import replace_widget
from ui.widget import Widget


class Test_Assembly(Widget):
    def __init__(self, img_path=None, text=None, widget=None):
        super().__init__()
        self.set_img(img_path=img_path)
        self.set_text(text=text)
        self.set_widget(widget=widget)
        self.resizeEvent()

    def set_img(self, img_path=None):
        if img_path is not None:
            self.img = QPixmap(str(img_path))
            self.img_l.setVisible(True)
        else:
            self.img = None
            self.img_l.setVisible(False)

    def set_text(self, text=None):
        if text is not None:
            self.text = text
            self.text_l.setText(str(self.text))
            self.text_l.setVisible(True)
        else:
            self.text = None
            self.text_l.setVisible(False)

    def set_widget(self, widget=None):
        if widget is not None:
            replace_widget(self, "widget", widget)
            # widget attributes passtrough passtrough
            for attr in ["ok", "ko", "start", "stop", "reset"]:
                if hasattr(self.widget, attr):
                    setattr(self, attr, getattr(self.widget, attr))
                else:
                    if hasattr(self, attr):
                        delattr(self, attr)
            if hasattr(widget, "set_parent_assembly_widget"):
                widget.set_parent_assembly_widget(weakref.ref(self))
            self.widget.setVisible(True)
        else:
            self.widget.setVisible(False)

    def resizeEvent(self, event=None):
        if self.img is not None:
            self.img_l.setPixmap(self.img.scaled(self.img_l.width(), self.img_l.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
