from lib.db import Users
from PyQt5.QtWidgets import QAbstractItemView
from ui.crud import Crud, Json_External_Dialog_Cell_Widget
from ui.helpers import replace_widget
from ui.widget import Widget


class Autotests_Archive(Widget):
    def __init__(self, printer=None):
        super().__init__()
        self.printer = printer
        session = Users.get_session()
        if session is not None and session.is_admin:
            crud_aliases = {
                "id": "Id",
                "time": "Data e ora",
                "user": "Operatore",
                "recipe": "Ricetta",
                "result": "Esito",
                "reason": "Motivo",
                "overridden": "Esito forzato",
                "test_data": "Dati del test",
            }
            readonly = ["id"]
        else:
            crud_aliases = {
                "time": "Data e ora",
                "user": "Operatore",
                "recipe": "Ricetta",
                "result": "Esito",
                "reason": "Motivo",
                "overridden": "Esito forzato",
                "test_data": "Dati del test",
            }
            readonly = True
        self.crud = Crud(
            "autotests",
            display_name="Archivio autotest",
            readonly=readonly,
            select=list(crud_aliases.keys()),
            fields_aliases=crud_aliases,
            widget_classes={
                "test_data": Json_External_Dialog_Cell_Widget,
            },
        )
        replace_widget(self, "crud_w", self.crud)
        self.selected = None
        self.print_b.setEnabled(False)
        self.crud.db_tw.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.crud.db_tw.setSelectionMode(QAbstractItemView.SingleSelection)
        self.crud.db_tw.itemSelectionChanged.connect(self.check)
        self.print_b.clicked.connect(self.print_label)

    def check(self):
        if not self.crud.modified:
            selected = self.crud.get_selected_rows()
            if len(selected) == 1:
                selected = selected[0] - 1   # - 1 because rn starts from 1 (filters line)
                if selected >= 0 and selected < len(self.crud.data_index):
                    selected = self.crud.data_index[selected]
                    self.selected = self.crud.db.table_model.get_by_id(selected)
                    self.print_b.setEnabled(True)
                    return
        self.selected = None
        self.print_b.setEnabled(False)

    def print_label(self):
        self.check()
        if self.selected is not None and self.printer is not None:
            self.printer.print_autotest_label(self.selected)
