from PyQt5.QtWidgets import QDialog

from core.models import Tag
from core.repositories import TagRepository
from ui.qt.dlg_tag_ui import Ui_dlgTag


class DlgTag(QDialog):
    def __init__(self, tag, parent=None):
        super().__init__(parent)
        self.tag = tag
        self.createWidgets()

    def createWidgets(self):
        self.ui = Ui_dlgTag()
        self.ui.setupUi(self)

        if self.tag.label:
            self.ui.lineTagLabel.setText(self.tag.label)

        self.ui.btnSave.clicked.connect(self.save)
        self.ui.btnCancel.clicked.connect(self.cancel)

    @classmethod
    def edit(cls, tag=None, parent=None):
        if tag is None:
            tag = Tag()
        dlg = cls(tag, parent)
        r = dlg.exec_()
        return r

    def ok(self):
        new_label = self.ui.lineTagLabel.text()
        if not new_label:
            return
        tag_repo = TagRepository()
        self.tag = new_label
        tag_repo.commit()
        self.done(1)

    def cancel(self):
        self.done(0)