import os
import sys
import UtilPack as util
from pathlib import Path
import VWorldAPIs as vw
import ExtEXIFData as exif

from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton, QVBoxLayout, QLineEdit, QHBoxLayout, QListWidget, QTableWidget, QRadioButton, QLabel, QFileDialog, QListWidgetItem
from PyQt5.QtGui import QPixmap, QTransform

QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)

class MyApp(QMainWindow):

    def __init__(self):
        super().__init__()
        self.initUI()
        self.loadINI()

    def closeEvent(self, event):
        event.accept()
        
    def initUI(self):
        layout = self.MakeUI()
            
        # 레이아웃을 윈도우에 적용
        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)
        self.setWindowTitle('Poles Database')
        self.move(100, 300)
        self.show()
    
    def loadINI(self):
        print("Load INI")
        
    def saveINI(self):
        print("Save INI")
    
    def MakeUI_Left_Top(self):
        label_SrcPath = QLabel("Source Path")
        self.edit_SrcPath = QLineEdit("", self)
        self.edit_SrcPath.setReadOnly(True) 
        btn_SrcPath_OK = QPushButton("...", self)
        btn_SrcPath_OK.clicked.connect(self.on_click_SourcePath)
        self.edit_SrcPath.setEnabled(False)
        btn_SrcPath_OK.setEnabled(False)

        layout01 = QHBoxLayout()
        layout01.addWidget(label_SrcPath)
        layout01.addWidget(self.edit_SrcPath)
        layout01.addWidget(btn_SrcPath_OK)
        
        label_ImgPath = QLabel("Image Path")
        self.edit_ImgPath = QLineEdit("", self)
        self.edit_ImgPath.setReadOnly(True)
        btn_ImgPath_OK = QPushButton("...", self)
        btn_ImgPath_OK.clicked.connect(self.on_click_ImagePath)

        layout02 = QHBoxLayout()
        layout02.addWidget(label_ImgPath)
        layout02.addWidget(self.edit_ImgPath)
        layout02.addWidget(btn_ImgPath_OK)

        self.btn_ParseImages = QPushButton("Parse!!", self)
        self.btn_ParseImages.clicked.connect(self.on_click_btn_ParseImages)
        self.btn_ParseImages.setMaximumWidth(410)
        
        layout = QVBoxLayout()
        layout.addLayout(layout01)
        layout.addLayout(layout02)
        layout.addWidget(self.btn_ParseImages)
        
        return layout
        
    def MakeUI_Left_Mid(self):
        # 이미지 목록
        self.list_Images = QListWidget(self)
        self.list_Images.itemSelectionChanged.connect(self.on_SelChanged_ImageList)
        self.list_Images.setMinimumWidth(100)
        self.list_Images.setMaximumWidth(200)

        # 이미지 정보 테이블
        self.list_Info = QListWidget(self)
        self.list_Info.setMinimumWidth(100)
        self.list_Info.setMaximumWidth(200)
        
        layout_r = QVBoxLayout()
        layout_r.addWidget(self.list_Info)
        
        layout = QHBoxLayout()
        layout.addWidget(self.list_Images)
        layout.addLayout(layout_r)
        
        return layout
    
    def MakeUI_left_Down(self):
        label_ExlPath = QLabel("DB(xlsx) Path")
        self.edit_ExlPath = QLineEdit("", self)
        self.edit_ExlPath.setReadOnly(True)
        btn_ExlPath_OK = QPushButton("OK", self)
        layout01 = QHBoxLayout()
        layout01.addWidget(label_ExlPath)
        layout01.addWidget(self.edit_ExlPath)
        layout01.addWidget(btn_ExlPath_OK)
        
        btn_Exl_Export = QPushButton("Export to EXCEL", self)
        btn_Exl_Export.clicked.connect(self.on_click_btn_ExportToExcel)
        
        layout = QVBoxLayout()
        layout.addLayout(layout01)
        layout.addWidget(btn_Exl_Export)
        
        return layout
    
    def MakeUI_Left(self):
        lsyout_lefttop = self.MakeUI_Left_Top()
        layout_leftmid = self.MakeUI_Left_Mid()
        layout_leftDwn = self.MakeUI_left_Down()
        
        layout = QVBoxLayout()
        layout.addLayout(lsyout_lefttop)
        layout.addLayout(layout_leftmid)
        layout.addLayout(layout_leftDwn)
        
        return layout
    
    def MakeUI(self):
        layout_L = self.MakeUI_Left()
        
        # show Image in middle Layout
        self.label_Image = QLabel(self)
        
        # Load Default Image
        pixmap = QPixmap("layoutImg.jpeg")
        scaled_Pix = pixmap.scaledToWidth(450)
        self.label_Image.setPixmap(scaled_Pix)
        self.label_Image.setMaximumWidth(450)
        
        # Show GPS Mapped map in Right Layout
        self.webview_map = QWebEngineView()
        self.webview_map.setFixedWidth(450)
        html_path = Path(__file__).resolve().parent / "sample_Event.html"
        self.webview_map.setUrl(QUrl.fromLocalFile(str(html_path)))

        # 레이아웃 설정
        layout = QHBoxLayout()
        layout.addLayout(layout_L)
        layout.addWidget(self.label_Image)
        layout.addWidget(self.webview_map)
        
        return layout

    def on_click_SourcePath(self):
        folder_path = QFileDialog.getExistingDirectory(self, '폴더 선택', '')
        self.edit_SrcPath.setText(folder_path)

    def on_click_ImagePath(self):
        folder_path = QFileDialog.getExistingDirectory(self, '폴더 선택', '')
        self.edit_ImgPath.setText(folder_path)

    def on_click_btn_ParseImages(self):
        self.btn_ParseImages.setEnabled(False)
        pathImage= self.edit_ImgPath.text()

        trgDirList = util.GetSubDirectories(pathImage)
            
        retImgList = []
        for dirName in trgDirList:
            if dirName.lower() in "thumb":
                continue

            imgSubDirPath = os.path.join(pathImage, dirName)
            contents = os.listdir(imgSubDirPath)
            
            for item in contents:
                name, ext = os.path.splitext(item)
                if ext.lower() == '.jpg':
                    imgPath = os.path.join(imgSubDirPath, item)
                    retImgList.append(imgPath)

        for img in  retImgList:
            item = QListWidgetItem(util.GetParentDirName(img, 0))
            listData = []
            listData.append(img)
            
            all_date, lat, lon = exif.GetDateInfo(img)
            listData.append(str(all_date))
            listData.append(str(lat))
            listData.append(str(lon))

            juso, area = vw.GetJusofromGPS(lat, lon)
            listData.append(area)
            listData.append(juso)

            listData.append(util.GetParentDirName(img, 0))
            listData.append(util.GetParentDirName(img, 1))
            item.setData(Qt.UserRole, listData)
            self.list_Images.addItem(item)
        
        self.btn_ParseImages.setEnabled(True)
        print("Parse END!")
    
    def on_click_btn_ExportToExcel(self):
        print("Excel!!")

    def on_SelChanged_ImageList(self):
        items = self.list_Images.selectedItems()
        for item in items:
            listData = item.data(Qt.UserRole)
            
            self.list_Info.clear()
            for content in listData:
                row = QListWidgetItem(content)
                self.list_Info.addItem(row)

            pixmap = QPixmap(listData[0])

            szLabel = self.label_Image.size()
            

            resized_pixmap = pixmap.scaled(100, 100)
            rotated_pixmap = resized_pixmap.transformed(QTransform().rotate(90))

            self.label_Image.setPixmap(pixmap)
            
    
    # def open_image(self):
    #     # 이미지 파일 열기 다이얼로그
    #     file_name, _ = QFileDialog.getOpenFileName(self, "Open Image File", "", "Images (*.png *.xpm *.jpg)")
        
    #     if file_name:
    #         # QPixmap을 사용해 이미지를 QLabel에 설정
    #         pixmap = QPixmap(file_name)
    #         self.label.setPixmap(pixmap)
    #         self.label.setScaledContents(True) 
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    app.setQuitOnLastWindowClosed(True)
    main_window = MyApp()
    #main_window.show()
    
    sys.exit(app.exec_())

