import requests, os
from PyQt5.QtWidgets import QWidget, QTextBrowser, QVBoxLayout
from PyQt5.QtCore import Qt
from PIL import Image
class TrademarkSearchDisplay(QWidget):
    def __init__(self, parent=None):
        super().__init__()
        self.initUI(parent)

    # def showEvent(self, event):
    #     super().showEvent(event)
    #     if self.parent() is not None:
    #         parent_geometry = self.parent().geometry()
    #         self.setGeometry(
    #             parent_geometry.x() + (parent_geometry.width() - self.width()) // 2,
    #             parent_geometry.y() + (parent_geometry.height() - self.height()) // 2,
    #             self.width(), self.height()
    #         )
    #     self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)


    def initUI(self, parent):

        self.setWindowTitle("도움말")
        if parent is not None:
            self.setModal(True)
            self.setParent(parent)
            # 위치를 부모 윈도우의 중앙으로 설정
            parent_geometry = parent.geometry()
            self.setGeometry(
                parent_geometry.x() + (parent_geometry.width() - 200) // 2,
                parent_geometry.y() + (parent_geometry.height() - 200) // 2,
                1200, 600
            )
            self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)

        else:
            self.resize(1200, 600)  # 단독 실행 시 크기 설정


        # self.setGeometry(100, 100, 1200, 600)
        self.setWindowTitle('Trademark Search Results')
        
        self.text_browser = QTextBrowser(self)
        self.text_browser.setOpenExternalLinks(True)  # Allows opening links
        
        layout = QVBoxLayout()
        layout.addWidget(self.text_browser)
        self.setLayout(layout)
    
    def display_api_results(self, data, elapsed_time):
        
        for item in data:
            downloaded_image_path = self.download_image(item.get("drawing_url"), item.get("ID"))

            html_content = f'''
            <div style="border: 1px solid #ccc; margin: 10px; padding: 10px;">
                <h2>{item.get("title")}</h2>
                <img src="{downloaded_image_path}" alt="Drawing Image" style="max-width: 100px;"><br>
                <strong>Application Date:</strong> {item.get("application_date")}<br>
                <strong>Publication Date:</strong> {item.get("publication_date")}<br>
                <strong>Registration Date:</strong> {item.get("registration_date")}<br>
                <strong>Applicant Name:</strong> {item.get("applicant_name")}<br>
                <strong>Full Text:</strong> {item.get("full_text")}<br>
                <strong>Application Status:</strong> {item.get("application_status")}<br>
                <strong>Classification Code:</strong> {item.get("classification_code")}<br>
            </div>
            '''
            self.text_browser.append(html_content)
        
    def display_web_results(self, data, elapsed_time):
        print(f"Processing results... Elapsed time: {elapsed_time}s")
        # data 딕셔너리 내의 키 중 'result_'로 시작하는 키를 찾아 그 값을 처리
        for key, item in data.items():
            print(f"Checking key: {key}")  # 로그 추가
            if key.startswith('result_'):  # 'result_'로 시작하는 키 확인
                print(f"Found valid key: {key}, Processing item...")  # 로그 추가
                if isinstance(item, dict):  # item이 딕셔너리인지 확인
                    print(f"Item is a dictionary. Generating HTML for item with title: {item.get('title')}")  # 로그 추가
                    
                    # 이미지 다운로드 시도
                    downloaded_image_path = self.download_image(item.get("drawing_url"), item.get("ID"))
                    if downloaded_image_path:
                        print(f"Image downloaded and saved to {downloaded_image_path}")
                        image_html = f'<img src="{downloaded_image_path}" style="width:100%; max-width:300px; height:auto;">'
                    else:
                        print("Failed to download image.")
                        image_html = 'Image not available'
                    
                    # HTML 콘텐츠 생성
                    html_content = f'''
                    <table style="width: 100%; border-collapse: collapse; border: 1px solid #ccc; margin-bottom: 20px;">
                        <tr>
                            <td style="text-align: left; padding-right: 10px;">Product Title:</td>
                            <td style="width: 30%; padding-left: 10px;">{item.get("title", "정보 없음")}</td>
                        </tr>
                        <tr>
                            <td rowspan="4" style="width: 40%; text-align: center; border-right: 2px solid #000;">
                                <img src="file:///{downloaded_image_path}" alt="Trademark Image" style="width: 100px; height: 100px;">

                            </td>   
                            <td style="width: 30%; text-align: right; padding-right: 10px;">Admin Status:</td>
                            <td style="width: 30%; padding-left: 10px;">{item.get("application_status", "정보 없음")}</td>
                        </tr>
                        <tr>
                            <td style="text-align: left; padding-right: 10px;">Product Category:</td>
                            <td style="width: 30%; padding-left: 10px;">{item.get("product_category", "정보 없음")} - {item.get("category_description", "정보 없음")}</td>
                        </tr>
                        <tr>
                            <td style="text-align: left; padding-right: 10px;">Applicant:</td>
                            <td style="width: 30%; padding-left: 10px;">{item.get("applicant_name", "정보 없음")}</td>
                        </tr>
                        <tr>
                            <td style="text-align: left; padding-right: 10px; border-right: 2px solid #000;">Publication Date:</td>
                            <td style="width: 30%; padding-left: 10px;">{item.get("publication_date", "정보 없음")}</td>
                        </tr>
                        <tr>
                            <td style="text-align: left; padding-right: 10px; border-right: 2px solid #000;">Registration Date:</td>
                            <td style="width: 30%; padding-left: 10px;">{item.get("registration_date", "정보 없음")}</td>
                        </tr>
                    </table>
                    <div style="margin-bottom: 40px;"></div> <!-- Additional separation for visual distinction -->
                    '''

                    self.text_browser.append(html_content)
                    print("HTML content appended to QTextBrowser.")  # 로그 추가
                else:
                    print(f"Error: Item associated with {key} is not a dictionary.")  # 오류 로그
            else:
                print(f"Ignored key: {key}")  # 무시된 키 로그


    def download_image(self, image_url, identifier):
        """Download an image and save it to a local directory."""
        # 현재 실행 중인 스크립트의 디렉토리 경로를 가져온다
        base_path = os.path.dirname(os.path.realpath(__file__))
        image_folder = os.path.join(base_path, "kipris_image")
        
        # kipris_image 폴더가 없다면 생성
        if not os.path.exists(image_folder):
            os.makedirs(image_folder)
        
        # 이미지 파일의 경로를 설정 (고유 식별자를 파일명으로 사용)
        image_path = os.path.join(image_folder, f"{identifier}.jpg")
        
        # 이미지 다운로드 및 저장
        response = requests.get(image_url)
        if response.status_code == 200:
            with open(image_path, 'wb') as file:
                file.write(response.content)
                image_path = self.resize_image(image_path)
            return image_path
        else:
            return None

    def resize_image(self, image_path, output_size=(100, 100)):
        try:
            with Image.open(image_path) as img:
                img_resized = img.resize(output_size)
                img_resized.save(image_path)
                return image_path
        except Exception as e:
            print(f"Error resizing image: {e}")
            return None



