# Gelistirici: Mahmut Murat OYMACI
# Iletisim: mahmutoymaci@gmail.com
# Tarih: 05/03/2026

import sys
sys.dont_write_bytecode = True
try:from pymxs import runtime as rt 
except:pass
if (rt.maxversion())[7] < 2026:
    from PySide2.QtWidgets import (
        QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QScrollArea, QComboBox, QSplitter,
        QLabel, QPushButton, QTextEdit, QSizePolicy
    )
    from PySide2.QtCore import Qt, QThread, Signal, QByteArray, QSize
    from PySide2.QtGui import QFont, QPixmap, QImage, QMovie
else:
    from PySide6.QtWidgets import (
        QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QScrollArea, QComboBox, QSplitter,
        QLabel, QPushButton, QTextEdit, QSizePolicy
    )
    from PySide6.QtCore import Qt, QThread, Signal, QByteArray, QSize
    from PySide6.QtGui import QFont, QPixmap, QImage, QMovie
import os
import json
from pathlib import Path

def gescre():
    app = QApplication.instance() or QApplication(sys.argv)
    screen = app.primaryScreen()
    size = screen.availableGeometry()
    dpi = screen.logicalDotsPerInch()
    return size.width(), size.height(), (dpi / 96.0)
    
screen_w, screen_h, scale = gescre()

class ReleasesDialog(QMainWindow):
    def __init__(self, selection_folder=None):
        super().__init__()
        self.selection_folder = selection_folder # acilista bir klasor adresi verilirse
        self.setAttribute(Qt.WA_DeleteOnClose) # pencereyi kapatildigi zaman bellekten temizle
        self.setWindowTitle("Sarfinet Releases")
        
        base_w = 800 * scale
        base_h = 900 * scale
        win_w = int(base_w)
        win_h = int(base_h)
        self.resize(win_w, win_h)
        self.setWindowFlags(self.windowFlags() | Qt.WindowCloseButtonHint)
        self.current_image_path = None
        self.setup_ui()
        self.setStyleSheet(f"""
            QPushButton {{
                min-height: {int(30 * scale)}px;
                min-width:  {int(80 * scale)}px;
            }}
            """)
    def setup_ui(self):
        central_widget = QWidget()
        central_widget.setStyleSheet("background-color: #444444;")
        self.setCentralWidget(central_widget)
        
        main_layout = QVBoxLayout(central_widget)
        margin = 10 * scale
        main_layout.setContentsMargins(margin,margin,margin,margin)
        main_layout.setSpacing(10)

        # --- 1. ÜST BÖLÜM (Resim + Kaydirici) ---
        upper_container = QWidget()
        upper_layout = QVBoxLayout(upper_container)
        # upper_layout.setContentsMargins(0, 0, 0, 0)

        self.image_container = QLabel("Please Chose Folder")
        self.image_container.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.image_container.setAlignment(Qt.AlignCenter)
        self.image_container.resize(self.width(),self.height()) # acilista buyut
        upper_layout.addWidget(self.image_container)

        self.thumbnail_scroll = QScrollArea()
        self.thumbnail_scroll.setFixedHeight(70*scale)
        self.thumbnail_scroll.setWidgetResizable(True)
        self.thumbnail_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.thumbnail_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        self.thumbnail_widget = QWidget()
        self.thumbnail_layout = QHBoxLayout(self.thumbnail_widget)
        self.thumbnail_layout.setContentsMargins(5, 5, 5, 5)
        self.thumbnail_layout.setSpacing(10)
        self.thumbnail_scroll.setWidget(self.thumbnail_widget)
        upper_layout.addWidget(self.thumbnail_scroll)

        # --- 2. ALT BÖLÜM (Release Notes) ---
        notes_container = QWidget()
        notes_container.resize(self.width(),1000*scale) # acilista buyut
        notes_inner_layout = QVBoxLayout(notes_container)
        notes_inner_layout.setContentsMargins(0, 0, 0, 0)

        lbl_notes_title = QLabel("Release Notes")
        lbl_notes_title.setFont(QFont("Arial", 10, QFont.Bold))
        lbl_notes_title.setStyleSheet("color: #ddd;")
        notes_inner_layout.addWidget(lbl_notes_title)

        self.notes_text = QTextEdit()
        self.notes_text.setReadOnly(True)
        self.notes_text.setStyleSheet("color: white; background-color: #646464; border-radius: 4px; padding: 5px;")
        notes_inner_layout.addWidget(self.notes_text)

        # --- 3. SPLITTER ---
        self.splitter = QSplitter(Qt.Vertical)
        self.splitter.addWidget(upper_container)
        self.splitter.addWidget(notes_container)
        self.splitter.setStretchFactor(0, 3) # Üst taraf daha genis baslasin
        self.splitter.setStretchFactor(1, 1) # Alt taraf daha dar baslasin
        self.splitter.splitterMoved.connect(self.on_splitter_moved)
        
        main_layout.addWidget(self.splitter)

        # --- 4. KONTROLLER ---
        controls_layout = QHBoxLayout()
        self.folder_menu = QComboBox()
        self.folder_menu.setMinimumWidth(150*scale)
        self.folder_menu.setMaximumWidth(250*scale)
        self.folder_menu.setPlaceholderText("Sarfinet Update")
        controls_layout.addWidget(self.folder_menu)

        self.close_button = QPushButton("Close")
        self.close_button.setCursor(Qt.PointingHandCursor)
        self.close_button.clicked.connect(self.close)
        self.close_button.setStyleSheet("QPushButton { background-color: #646464; color: white; border-radius: 4px; padding: 0 20px; }")
        controls_layout.addWidget(self.close_button)

        main_layout.addLayout(controls_layout)

        # --- KLASOR DEGISTIR ---
        self.search_dir = rt.sarfinet.getdir.releases
        if os.path.exists(self.search_dir):
            klasorler = [d for d in os.listdir(self.search_dir) if os.path.isdir(os.path.join(self.search_dir, d))]
            klasorler.sort(key=str.lower)
            self.folder_menu.addItems(klasorler)
            
            if klasorler:
                last_index = len(klasorler) - 1
                self.folder_menu.setCurrentIndex(last_index)
                if self.selection_folder:
                    self.load_thumbnails(self.selection_folder)
                else:
                    self.load_thumbnails(os.path.join(self.search_dir, klasorler[last_index]))

        self.folder_menu.currentTextChanged.connect(self.on_folder_changed)
        
    def on_splitter_moved(self, pos, index):
        """Splitter çubugu kaydirildiginda çalisir"""
        if hasattr(self, 'current_image_path') and self.current_image_path:
            self.update_main_image(self.current_image_path)
            
    def resizeEvent(self, event):
        """Pencere boyutu her degistiginde bu fonksiyon otomatik çalisir"""
        if self.current_image_path:
            self.update_main_image(self.current_image_path)
        super().resizeEvent(event)
            
    def on_folder_changed(self, selected_folder_name):
        if not selected_folder_name: return
        
        # Mevcut thumbnail'lari temizle
        while self.thumbnail_layout.count():
            item = self.thumbnail_layout.takeAt(0)
            widget = item.widget()
            if widget:
                widget.setParent(None)
                widget.deleteLater()
                
        # Yeni resimleri yükle
        target_path = os.path.join(self.search_dir, selected_folder_name)
        self.load_thumbnails(target_path)

    def scaled_size_keep_aspect(self, movie: QMovie, target_width: int, target_height: int) -> QSize:
        """QMovie için orantılı ölçek hesaplar."""
        movie.jumpToFrame(0)
        original = movie.currentPixmap().size()
        if original.isEmpty():
            return QSize(target_width, target_height)
        w, h = original.width(), original.height()
        scale = min(target_width / w, target_height / h)
        return QSize(int(w * scale), int(h * scale))

    def load_thumbnails(self, folder_path):
        if not os.path.exists(folder_path): return
        valid_ext = ('.md', '.txt')
        txt_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.lower().endswith(valid_ext)]
        txt_files.sort()
        if len(txt_files) != 0:
            f = open(txt_files[-1], encoding='utf-8')
            self.notes_text.setMarkdown(f.read())
        valid_ext = ('.jpg', '.jpeg', '.png', '.gif')
        images = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.lower().endswith(valid_ext)]
        images.sort()
        for i, yol in enumerate(images):
            thumb = QLabel()
            size = 60 * scale
            thumb.setFixedSize(size, size)
            thumb.setCursor(Qt.PointingHandCursor)
            thumb.setStyleSheet("border: 1px solid #888;")
            thumb.setAlignment(Qt.AlignCenter)

            pix = QPixmap(yol)
            if not pix.isNull():
                thumb.setPixmap(pix.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation))

            thumb.mousePressEvent = lambda e, p=yol: self.update_main_image(p)
            self.thumbnail_layout.addWidget(thumb)

            if i == 0:
                self.update_main_image(yol)

    def update_main_image(self, path):
        self.current_image_path = path

        # Önceki movie varsa durdur ve temizle
        if hasattr(self, '_main_movie') and self._main_movie is not None:
            self._main_movie.stop()
            self._main_movie = None

        if path.lower().endswith('.gif'):
            movie = QMovie(path)
            label_width = self.width()
            label_height = self.image_container.height()
            scaled = self.scaled_size_keep_aspect(movie, label_width, label_height)
            movie.setScaledSize(scaled)
            self.image_container.setMovie(movie)
            movie.start()
            self._main_movie = movie
        else:
            self.image_container.setMovie(None)
            pixmap = QPixmap(path)
            if not pixmap.isNull():
                label_width = self.image_container.width()
                label_height = self.image_container.height()
                scaled_pixmap = pixmap.scaled(
                    label_width,
                    label_height,
                    Qt.KeepAspectRatio,
                    Qt.SmoothTransformation
                )
                self.image_container.setPixmap(scaled_pixmap)
        self.image_container.setMinimumSize(60*scale, 60*scale)
        
    def handle_close(self):
        self.close()

def redi(selection_folder=None):
    global reldialog
    try:
        reldialog.close()
        reldialog.deleteLater()
    except:
        pass

    reldialog = ReleasesDialog(selection_folder)
    reldialog.show()
if __name__ == "__main__":
    redi()