import os.path
import sys
import weakref

from PyQt5 import QtSvg
from PyQt5.QtCore import Qt

from lib.helpers import timing
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QKeySequence, QPixmap
from PyQt5.QtWidgets import QShortcut, QApplication, QVBoxLayout

from lxml import etree

from ui import Widget


class Test_Instructions_Reminder(Widget):
    def __init__(self, recipe=None, bench_name="generic"):
        super().__init__()
        self.bench_name = bench_name
        self.recipe=recipe
        self.svgWidget=None
        self.svg_root=None
        self.flag=False
        self.inputs={}
        self.svg_widget=QtSvg.QSvgWidget()
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.svg_widget)
        self.svg_w.setLayout(self.layout)
        self.svg_path=os.path.join("config","instruction_images",self.bench_name,"")
        self.timer = QTimer()
        self.timer.timeout.connect(self.toggle_icons)

        self.start()

    def start(self, recipe=None, step=None, pieces=None):

        svg_path=f"{self.svg_path}{self.recipe}.svg"
        if not os.path.exists(svg_path):
            svg_path=f"{self.svg_path}DEFAULT.svg"
        self.svg_root = etree.parse(svg_path)
        self.svg_str = etree.tostring(self.svg_root)
        self.svg_str=etree.tostring(self.svg_root)

        self.monitored_ids=self.svg_root.xpath(f'''.//*[starts-with(@id, 'sensor_')]''')
        self.tape_ids=self.svg_root.xpath(f'''.//*[starts-with(@id, 'tape_')]''')
        self.timer.start(1000)
    def toggle_icons(self):
        self.flag = not self.flag

        for elem in self.tape_ids:
            if self.flag:
                self.show_tape(elem)
            else:
                self.hide_tape(elem)


        self.show_svg()


    def show_icon(self,id):
        id.set("display", "inline")

    def hide_icon(self,id):
            id.set("display", "none")

    def show_tape(self,id):
        id.attrib["{http://www.w3.org/1999/xlink}href"]= f"{self.svg_path}img/tape_black.png"
        id.set("display", "inline")

    def hide_tape(self,id):
        id.set("display", "none")

    def show_svg(self):
        self.svg_str = etree.tostring(self.svg_root)
        self.svg_widget.load(self.svg_str)
        QApplication.processEvents()
