
import os
import re
import html
from typing import Tuple


from qgis.PyQt import QtWidgets, uic
from qgis.PyQt.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QWidget, QDialog
from PyQt5.QtGui import QPixmap, QImage, QPainter
from PyQt5.QtCore import Qt
from PyQt5 import QtGui
from qgis.PyQt.QtCore import QUrl
from qgis.PyQt.QtGui import QDesktopServices


import common
from urbanq.logging.logging_config import logger



FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'ImageDescription_dockwidget_base.ui'))


class ImageDescriptionDockWidget(QDialog, FORM_CLASS):  
    def __init__(self, parent=None, option=None):
        
        super(ImageDescriptionDockWidget, self).__init__(parent)  
        
        
        
        
        
        self.setupUi(self)

        
        job_index = common.job_info.get("job_index")
        job_title = common.job_info.get("job_title")
        job_class = common.job_info.get("job_class")
        job_tooltip, job_link = self.html_tooltip_to_text(common.job_info.get("job_tooltip"))

        
        [widget.setProperty("class", "boldText") for widget in [self.qlabel_1537, self.qlabel_4071, self.btnViewVideo]]

        
        
        
        self.image_path = os.path.join(self.get_current_folder(), 'ImageDescription', job_class, f"슬라이드{job_index + 1}.jpg")

        
        self.qlabel_1537.setText(job_title[2:])
        self.qlabel_3527.setText(job_tooltip)

        
        self.btnViewVideo.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(job_link)))

    @staticmethod
    def get_current_folder():
        
        return os.path.dirname(os.path.abspath(__file__))

    @staticmethod
    def to_two_digits(number: int) -> str:
        
        return str(number).zfill(2)

    @staticmethod
    def html_tooltip_to_text(html_tooltip: str) -> Tuple[str, str]:
        
        try:
            if not html_tooltip:
                return "", ""

            
            text = re.sub(r'<\s*(p|br)\s*/?>', '\n', html_tooltip)

            
            text = re.sub(r'<[^>]+>', '', text)

            
            text = html.unescape(text)

            
            if '||' in text:
                body, link = text.split('||', 1)  
                return body.strip(), link.strip()

            return text.strip(), ""

        except Exception as e:
            logger.error("에러 발생: %s", e, exc_info=True)
            return "", ""

    def showEvent(self, event):
        
        try:
            super().showEvent(event)
            
            self.set_image_to_label(self.secondDescription_image, self.image_path)

        except Exception as e:
            logger.error("에러 발생: %s", e, exc_info=True)

    def set_image_to_label(self, qgraphicsview, image_path):
        
        try:
            
            image = QImage(image_path)
            if image.isNull():
                logger.error("에러 발생: %s", f"이미지를 찾을 수 없습니다: {image_path}", exc_info=True)
                return

            
            pixmap = QPixmap.fromImage(image)

            
            scene = QtWidgets.QGraphicsScene()
            qgraphicsview.setScene(scene)

            
            pixmap_item = QtWidgets.QGraphicsPixmapItem(pixmap)
            pixmap_item.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable)  
            scene.addItem(pixmap_item)

            
            image_ratio = pixmap.width() / pixmap.height()

            
            parent_width = qgraphicsview.parent().width()
            calculated_height = int(parent_width / image_ratio)
            parent_height = max(calculated_height, qgraphicsview.parent().height())
            qgraphicsview.resize(parent_width, parent_height)

            
            qgraphicsview.setRenderHint(QtGui.QPainter.Antialiasing)
            qgraphicsview.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)

            
            pixmap_item.setTransformationMode(Qt.SmoothTransformation)

            
            qgraphicsview.fitInView(pixmap_item, Qt.KeepAspectRatio)
            qgraphicsview.setAlignment(Qt.AlignHCenter | Qt.AlignTop)

            
            scale_factor = 1.15

            def wheel_event(event):
                
                if event.angleDelta().y() > 0:
                    qgraphicsview.scale(scale_factor, scale_factor)  
                else:
                    qgraphicsview.scale(1 / scale_factor, 1 / scale_factor)  

            
            qgraphicsview.wheelEvent = wheel_event

            def resize_event(event):
                
                if pixmap_item:
                    
                    qgraphicsview.setRenderHint(QtGui.QPainter.Antialiasing)
                    qgraphicsview.setRenderHint(QtGui.QPainter.SmoothPixmapTransform)

                    
                    pixmap_item.setTransformationMode(Qt.SmoothTransformation)

                    
                    qgraphicsview.fitInView(pixmap_item, Qt.KeepAspectRatio)
                    qgraphicsview.setAlignment(Qt.AlignHCenter | Qt.AlignTop)

                QtWidgets.QGraphicsView.resizeEvent(qgraphicsview, event)

            qgraphicsview.resizeEvent = resize_event

        except Exception as e:
            logger.error("에러 발생: %s", e, exc_info=True)

    def set_fileResults(self, num=1):
        
        try:
            return True

        except Exception as e:
            logger.error("에러 발생: %s", e, exc_info=True)
            return False
