import os
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import uic
import pandas as pd
import shutil

import subprocess
# from inference import run_AI

def resource_path(relative_path):
    base_path = getattr(
        sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__))
    )
    return os.path.join(base_path, relative_path)

form = resource_path("input_output.ui")
form_class = uic.loadUiType(form)[0]


class WindowClass(QMainWindow, form_class):

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.btnInput.clicked.connect(self.fileload)
        self.btnAI.clicked.connect(self.AIDetection)

        self.btnExcelDownload.clicked.connect(self.downloadTable)
        self.btnCADDownload.clicked.connect(self.downloadCAD)

        self.imageList = []

    def fileload(self):
        for i in reversed(range(self.inputImages.count())):
            widget = self.inputImages.itemAt(i).widget()
            self.inputImages.removeWidget(widget)
            widget.setParent(None)
            
        image_filter = "이미지 파일 (*.png *.jpg *.bmp *.gif *.jpeg, *.tiff, *.tif)"
        self.imageList, _ = QFileDialog.getOpenFileNames(self, "이미지 파일 업로드", filter=image_filter)
    
        self.inputImageWidget = QWidget()
        self.inputImageLayout = QGridLayout(self.inputImageWidget)

        row, col = 0, 0
        for image_path in self.imageList:
            pixmap = QPixmap(image_path)
            label = QLabel()
            label.setPixmap(pixmap)
            label.setScaledContents(True)
            label.setFixedSize(300, 250)

            file_name_label = QLabel(os.path.basename(image_path))
            self.inputImageLayout.addWidget(label, row, col)
            self.inputImageLayout.addWidget(file_name_label, row + 1, col)

            col += 1
            if col == 2:
                col = 0
                row += 2

        scrollArea = QScrollArea()
        scrollArea.setWidgetResizable(True)
        scrollArea.setWidget(self.inputImageWidget)
        self.inputImages.addWidget(scrollArea)

    def AIDetection(self):
        if not self.imageList:
            QMessageBox.warning(self, "알림", "이미지 파일을 업로드해주세요.", QMessageBox.Ok)
            return
        
        self.outputImages.clear()

        # The path where you want to save the text file
        output_file_path = "./image_paths.txt"
        with open(output_file_path, "w") as file:
            for path in self.imageList:
                file.write(path + "\n")

        # run_AI()
        subprocess.run(['python', 'inference.py'])

        ## 1. stitching ##
        stitching_img_path = './results/data1/panorama.jpg'
        image_label = QLabel()
        pixmap = QPixmap(stitching_img_path)
        image_label.setPixmap(pixmap)
        image_label.setScaledContents(True)
        image_label.setAlignment(Qt.AlignCenter)
        self.outputImages.addTab(image_label, 'Stitching')

        ## 2. detection ##
        detection_img_path = './results/data1/panorama_detected.jpg'
        image_label = QLabel()
        pixmap = QPixmap(detection_img_path)
        image_label.setPixmap(pixmap)
        image_label.setScaledContents(True)
        image_label.setAlignment(Qt.AlignCenter)
        self.outputImages.addTab(image_label, 'Detection')

        ## 3. contour ##
        detection_img_path = './results/data1/contour_panorama_detected.jpg'
        image_label = QLabel()
        pixmap = QPixmap(detection_img_path)
        image_label.setPixmap(pixmap)
        image_label.setScaledContents(True)
        image_label.setAlignment(Qt.AlignCenter)
        self.outputImages.addTab(image_label, 'Contour')

        ## 4. CAD ##
        image_path = './results/data1/CAD_FORMAT.svg'
        image_label = QLabel()
        pixmap = QPixmap(image_path)
        image_label.setPixmap(pixmap)
        image_label.setScaledContents(True)
        image_label.setAlignment(Qt.AlignCenter)
        self.outputImages.addTab(image_label, 'CAD')

        ## 5. Table ##
        # Table
        csv_path = './results/data1/detection_coor.csv'
        df = pd.read_csv(csv_path)
        class_data = {'class_1': {'count': 0, 'areas': 0},
                      'class_2': {'count': 0, 'areas': 0},
                      'class_3': {'count': 0, 'areas': 0},
                      'class_4': {'count': 0, 'areas': 0}}

        for idx, row in df.iterrows():
            label = row['label']
            area = (row['x2'] - row['x1']) * (row['y2'] - row['y1'])
            class_data[label]['count'] += 1
            class_data[label]['areas'] += area

        for col_idx, value in enumerate(class_data.values()):
            item_count = QTableWidgetItem(str(value['count']))
            item_areas = QTableWidgetItem(str(value['areas']))
            self.outputTable.setItem(0, col_idx, item_count)
            self.outputTable.setItem(1, col_idx, item_areas)

    def downloadTable(self):
        file_path, _ = QFileDialog.getSaveFileName(self, "Download Excel", "excel_file.xlsx", "Excel Files (*.xlsx)")
        if file_path:
            # Gather data from the table
            data = []
            for row in range(self.outputTable.rowCount()):
                row_data = []
                for column in range(self.outputTable.columnCount()):
                    item = self.outputTable.item(row, column)
                    row_data.append(item.text() if item is not None else '')
                data.append(row_data)

            # Create DataFrame
            df = pd.DataFrame(data, columns=['균열', '박리/박락', '백태', '철근 노출'])

            # Check if the DataFrame has exactly two rows
            if len(df) == 2:
                df.index = ['수량', '총면적(pixel)']
            else:
                # Handle the case where the number of rows is not two
                print("Error: DataFrame does not have exactly two rows.")
                return

            # Create a Pandas Excel writer using XlsxWriter as the engine
            with pd.ExcelWriter(file_path, engine='xlsxwriter') as writer:
                # Write DataFrame to the Excel file
                df.to_excel(writer, sheet_name='Crack Result')

                # Get the xlsxwriter workbook and worksheet objects
                worksheet = writer.sheets['Crack Result']

                # Set the column width
                for i in range(df.shape[1] + 1):  # +1 to include the index column
                    worksheet.set_column(i, i, 15)

    def downloadCAD(self):
        file_path = './results/data1/dxf_file.dxf'
        download_path, _ = QFileDialog.getSaveFileName(self, "Download DXF", "cad_file.dxf", "DXF Files (*.dxf)")

        if download_path:
            try:
                shutil.copyfile(file_path, download_path)
                print(f"다운로드 성공: {download_path}")
            except Exception as e:
                print(f"다운로드 실패: {e}")




if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWindow = WindowClass()
    myWindow.setWindowTitle("SSIMS (Auto concrete damage detector)")
    myWindow.show()
    app.exec_()