import sys
from PyQt5.QtWidgets import QApplication, QMessageBox, QSizePolicy, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QTextEdit, QGridLayout
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt, QByteArray, QBuffer, QIODevice
from kipris_web_from_playwright import WebScraper

class MainApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.scraper = WebScraper()
        self.scraper.setup_browser()
        

    def initUI(self):
        # 검색 레이아웃
        searchLayout = QHBoxLayout()
        self.searchLabel = QLabel('검색어 입력:', self)
        self.searchLineEdit = QLineEdit(self)
        self.searchLineEdit.returnPressed.connect(self.start_search)
        self.searchButton = QPushButton('검색 실행', self)
        self.searchButton.clicked.connect(self.start_search)

        searchLayout.addWidget(self.searchLabel)
        searchLayout.addWidget(self.searchLineEdit)
        searchLayout.addWidget(self.searchButton)

        # 로그 레이아웃
        logLayout = QVBoxLayout()
        self.logTextEdit = QTextEdit(self)
        self.logTextEdit.setReadOnly(True)

        logLayout.addWidget(self.logTextEdit)

        # 메인 레이아웃
        mainLayout = QVBoxLayout()
        mainLayout.addLayout(searchLayout)
        mainLayout.addLayout(logLayout)

        self.setLayout(mainLayout)
        self.setWindowTitle('Web Scraper')
        self.setGeometry(300, 300, 300, 400)

    def wrap_text(self, text, width=40):
        """주어진 너비에 맞게 텍스트를 줄바꿈합니다."""
        words = text.split()
        wrapped_text = ''
        line_length = 0

        for word in words:
            if line_length + len(word) + 1 > width:
                wrapped_text += '\n'
                line_length = 0
            wrapped_text += word + ' '
            line_length += len(word) + 1

        return wrapped_text.strip()

    def start_search(self):
        term = self.searchLineEdit.text()
        if not term:
            self.logTextEdit.append("검색어를 입력해주세요.")
            return
        
        self.logTextEdit.append("검색을 시작합니다...")
        results = self.scraper.search_for_term(term)
        if results:
            self.logTextEdit.append("검색 완료. 결과를 처리합니다...")
            self.show_results(results)
        else:
            self.logTextEdit.append("검색 결과가 없거나 오류가 발생했습니다.")
            QMessageBox.information(self, "검색 결과 없음", "검색 결과가 없으므로 지재권에 안심하시면 됩니다.", QMessageBox.Ok)


    def show_results(self, results):

        try:
            # 결과 위젯 생성
            self.results_widget = QWidget()
            layout = QVBoxLayout()
            self.results_widget.setLayout(layout)

            # 결과 갯수 확인 및 레이아웃 동적 생성
            total_count = int(results['total_count'])
            set_count = min(total_count, 10)
            grid_layout = QGridLayout()
            layout.addLayout(grid_layout)
            grid_index = 0
            grid_columns = 5

            for i in range(1, set_count + 1):
                result_key = f"result_{i}"
                if result_key in results:
                    result = results[result_key]

                    # 테두리 설정
                    border_style = ''
                    if result['admin_status'] == '등록':
                        border_style = 'border: 4px solid red;'
                    elif result['admin_status'] == '공고':
                        border_style = 'border: 3px solid black;'
                        
                    # 각 결과에 대한 레이아웃 생성
                    item_layout = QVBoxLayout()
                    item_widget = QWidget()  # 위젯 생성

                    # item_layout의 크기 정책 설정
                    item_widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.MinimumExpanding)

                    # 이미지 처리
                    image_label = QLabel()
                    image_label.setFixedSize(150, 150)
                    image_data = self.scraper.fetch_image_data(result['IDimageURL'])
                    pixmap = QPixmap()
                    pixmap.loadFromData(image_data)
                    # QLabel의 크기에 맞게 이미지 크기 조정
                    scaled_pixmap = pixmap.scaled(image_label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
                    image_label.setPixmap(scaled_pixmap)
                    # QLabel의 가로 세로 중앙에 이미지 표시
                    image_label.setAlignment(Qt.AlignCenter)
                    # 이미지 표시 위젯의 크기 조정 정책 설정
                    image_label.setScaledContents(True)

                    #이미지 중앙배치를 위해
                    horizontal_layout = QHBoxLayout()
                    horizontal_layout.addWidget(image_label)
                    horizontal_layout.setAlignment(Qt.AlignCenter)
                    item_layout.addLayout(horizontal_layout)

                    # item_layout.addWidget(image_label)

                    # 정보 텍스트
                    # info_text = f"상표권명: {result['title']}\n등록상태: {result['admin_status']}\nCategory: {result['product_category']}\nApplicant: {result['applicant']}\nPublication Date: {result['publication_date']}\nRegistration Date: {result['registration_date']}"
                    info_text = f"<span style='font-size: 11pt; font-weight: bold; text-decoration: underline;'>상표권명: {result['title']}</span><br>\n" \
                                f"<span style='font-size: 11pt; font-weight: bold; text-decoration: underline;'>등록상태: {result['admin_status']}</span><br>\n" \
                                f"<span style='font-size: 9pt;'>카테고리: {result['product_category']}</span><br>\n" \
                                f"<span style='font-size: 9pt;'>권리자: {result['applicant']}</span><br>\n" \
                                f"<span style='font-size: 9pt;'> {result['publication_date']}</span><br>\n" \
                                f"<span style='font-size: 9pt;'> {result['registration_date']}</span>"

                    info_label = QLabel(info_text)
                    info_label.setToolTip(self.wrap_text(result['category_description'], 50))
                    image_label.setToolTip(self.wrap_text(result['category_description'], 50))
                    item_layout.addWidget(info_label)

                    image_label.setStyleSheet(border_style)
                    info_label.setStyleSheet(border_style)

                    # 레이아웃에 위젯 추가
                    row = grid_index // grid_columns
                    col = grid_index % grid_columns
                    grid_layout.addLayout(item_layout, row, col)
                    grid_index += 1

            # 결과 위젯에 닫기 버튼 추가
            close_button = QPushButton("Close")
            close_button.clicked.connect(self.close_results_widget)
            layout.addWidget(close_button)

            # 결과 위젯을 메인 윈도우에 추가
            self.results_widget.setGeometry(300, 300, 600, 300)  # 위치와 크기 설정
            self.results_widget.setWindowTitle('Search Results')  # 타이틀 설정
            self.results_widget.show()

        except Exception as e:
            print(f"Error displaying results: {e}")


    def close_results_widget(self):
        # 결과 위젯닫기 함수를 호출할 때 사용하는 메서드
        self.results_widget.close()


    def closeEvent(self, event):
        self.scraper.close_browser()
        event.accept()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MainApp()
    ex.show()
    sys.exit(app.exec_())
