from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QVBoxLayout, QLabel, QDialog, QWidget
import subprocess
import shlex
import logging
from ui.widget import Widget


class LastCommit(Widget):
    def __init__(self):
        # Skip the Widget.__init__ that loads UI file and call QWidget.__init__ directly
        QWidget.__init__(self)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle("LAST COMMIT")
        self.log = logging.getLogger(f"{self.__class__.__name__} ({id(self)})")

        # Create layout
        layout = QVBoxLayout()
        self.setLayout(layout)

        # Create labels for commit info
        self.date_label = QLabel("Data: ")
        self.author_label = QLabel("Autore: ")
        self.description_label = QLabel("Descrizione: ")

        # Add labels to layout
        layout.addWidget(self.date_label)
        layout.addWidget(self.author_label)
        layout.addWidget(self.description_label)

        # Get and display commit info
        self.get_last_commit_info()

    def get_last_commit_info(self):
        try:
            # Get last commit date
            date_cmd = shlex.split("git log -1 --format=%cd")
            date_result = subprocess.run(date_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            commit_date = date_result.stdout.decode("utf-8").strip()

            # Get last commit author
            author_cmd = shlex.split("git log -1 --format=%an")
            author_result = subprocess.run(author_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            commit_author = author_result.stdout.decode("utf-8").strip()

            # Get last commit message
            msg_cmd = shlex.split("git log -1 --format=%s")
            msg_result = subprocess.run(msg_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            commit_msg = msg_result.stdout.decode("utf-8").strip()

            # Update labels
            self.date_label.setText(f"Data: {commit_date}")
            self.author_label.setText(f"Autore: {commit_author}")
            self.description_label.setText(f"Descrizione: {commit_msg}")
        except Exception as e:
            self.date_label.setText("Errore nel recupero delle informazioni")
            self.author_label.setText("Errore")
            self.description_label.setText(str(e))
