import argparse
import sip
from PyQt5.QtCore import pyqtSignal
from ui.window import Window

parser = argparse.ArgumentParser(prog='STTEN', description='Leak test system',add_help=False)
parser.add_argument('-w', '--width')
parser.add_argument('-h', '--height')
args,unspec = parser.parse_known_args()

class Main_Window(Window):
    do = pyqtSignal(dict)
    run_request = pyqtSignal(object, list, dict)

    @staticmethod
    def run_request_handler(fn, a, ka):
        fn(*a, **ka)

    def __init__(self):
        super().__init__()
        self.do.connect(self._do)
        self.run_request.connect(self.run_request_handler)
        # print("MAIN_WINDOW  ", str(int(QThread.currentThreadId())), flush=True)

        if "width" in args:
            if args.width is not None:
                self.setFixedWidth(int(args.width))
        if "height" in args:
            if args.height is not None:
                self.setFixedHeight(int(args.height))

    @staticmethod
    def _do(config):
        return config["f"](*config.get("a", []), **config.get("k", {}))

    def open_tab(self, widget):
        self.setCentralWidget(widget)

    def open_window(self, widget, show=True, maximized=False):
        wt = widget.__class__.__name__
        if wt not in self.windows or self.windows[wt] is None or sip.isdeleted(self.windows[wt]):
            w = Window()
            self.windows[wt] = w
            w.setCentralWidget(widget)
            if show:
                if maximized:
                    w.showMaximized()
                else:
                    w.show()
            return w
        else:
            self.windows[wt].activateWindow()
            return self.windows[wt]
