import sys
import os
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QMessageBox
from PyQt5.QtCore import Qt
from PIL import Image

class DropLabel(QLabel):
    """
    A QLabel subclass that accepts dragged files.
    When image files are dropped, they are converted to a 24-bit RLE-compressed TGA.
    """
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setText("Drag and drop images here")
        self.setAlignment(Qt.AlignCenter)
        self.setStyleSheet("QLabel { border: 4px dashed #aaa; font-size: 16px; }")
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        # Accept the event if it contains URLs (files)
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
        else:
            event.ignore()

    def dropEvent(self, event):
        urls = event.mimeData().urls()
        if not urls:
            return

        converted_files = []
        errors = []

        # Process each dropped file
        for url in urls:
            file_path = url.toLocalFile()
            if not os.path.isfile(file_path):
                continue  # Skip if not a file

            try:
                # Open the image using Pillow
                img = Image.open(file_path)
                # Convert to RGB to force a 24-bit image (removes alpha channel if present)
                img = img.convert("RGB")
                # Create the new file name in the same folder with .tga extension
                base, _ = os.path.splitext(file_path)
                new_file = base + ".tga"
                # Save as TGA with RLE compression
                img.save(new_file, format="TGA", rle=True)
                converted_files.append(new_file)
            except Exception as e:
                errors.append(f"Failed to convert {file_path}:\n{str(e)}")

        # Notify the user about the conversion results
        if converted_files:
            QMessageBox.information(self, "Conversion Complete",
                                    "The following files were converted:\n" + "\n".join(converted_files))
        if errors:
            QMessageBox.critical(self, "Conversion Errors", "\n".join(errors))

class MainWindow(QMainWindow):
    """
    The main window containing the drop area.
    """
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Image to TGA Converter")
        self.resize(400, 300)

        # Set up the central widget with a vertical layout
        central_widget = QWidget()
        layout = QVBoxLayout(central_widget)

        # Add our drop label to the layout
        self.drop_label = DropLabel(self)
        layout.addWidget(self.drop_label)

        self.setCentralWidget(central_widget)

def main():
    # Create the Qt Application
    app = QApplication(sys.argv)
    # Create and show the main window
    window = MainWindow()
    window.show()
    # Run the application's event loop
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
