import RLPy
import os
from PySide2.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QPushButton, QLineEdit, QLabel, QApplication
from PySide2.QtCore import Qt

rl_plugin_info = {
    "ap": "iClone",
    "ap_version": "8.0"
}

class FrameWandererWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.saved_frame_number = 0
        self.init_ui()

    def init_ui(self):
        main_layout = QVBoxLayout()

        # 1. Step size input
        input_layout = QHBoxLayout()
        input_label = QLabel("Step Size (Frames):")
        self.step_input = QLineEdit()
        self.step_input.setText("50")  
        self.step_input.setAlignment(Qt.AlignCenter)
        input_layout.addWidget(input_label)
        input_layout.addWidget(self.step_input)

        # 2. Timeline navigation buttons
        snap_button_layout = QHBoxLayout()
        self.btn_prev = QPushButton("◀ Snap Back")
        self.btn_next = QPushButton("Snap Forward ▶")
        
        self.btn_prev.clicked.connect(lambda: self.move_timeline(-1))
        self.btn_next.clicked.connect(lambda: self.move_timeline(1))
        
        snap_button_layout.addWidget(self.btn_prev)
        snap_button_layout.addWidget(self.btn_next)

        # 3. Frame memory buttons
        memo_button_layout = QHBoxLayout()
        self.btn_remember = QPushButton("📌 Remember Frame")
        self.btn_return = QPushButton("🎯 Go to Remembered")
        
        self.btn_remember.clicked.connect(self.remember_current_frame)
        self.btn_return.clicked.connect(self.return_to_remembered_frame)
        
        memo_button_layout.addWidget(self.btn_remember)
        memo_button_layout.addWidget(self.btn_return)

        main_layout.addLayout(input_layout)
        main_layout.addLayout(snap_button_layout)
        main_layout.addLayout(memo_button_layout)
        self.setLayout(main_layout)

    def move_timeline(self, direction):
        """Moves the playhead and snaps to the next multiple of step size"""
        try:
            step_size = int(self.step_input.text())
            if step_size <= 0: 
                step_size = 50
        except ValueError:
            step_size = 50
            self.step_input.setText("50")

        fps = RLPy.RGlobal.GetFps()
        current_time = RLPy.RGlobal.GetTime()
        current_frame = RLPy.GetFrameIndex(current_time, fps)
        
        # Calculate snapped frame index
        if direction == 1:
            new_frame = ((current_frame // step_size) + 1) * step_size
        else:
            if current_frame % step_size == 0:
                new_frame = current_frame - step_size
            else:
                new_frame = (current_frame // step_size) * step_size
        
        # Clamp to timeline boundaries
        start_frame = RLPy.GetFrameIndex(RLPy.RGlobal.GetStartTime(), fps)
        end_frame = RLPy.GetFrameIndex(RLPy.RGlobal.GetEndTime(), fps)
        new_frame = max(start_frame, min(new_frame, end_frame))

        new_frame_time = RLPy.IndexedFrameTime(new_frame, fps)
        RLPy.RGlobal.SetTime(new_frame_time)

    def remember_current_frame(self):
        fps = RLPy.RGlobal.GetFps()
        current_time = RLPy.RGlobal.GetTime()
        self.saved_frame_number = RLPy.GetFrameIndex(current_time, fps)
        print(f"[Wanderer] Frame {self.saved_frame_number} remembered.")

    def return_to_remembered_frame(self):
        fps = RLPy.RGlobal.GetFps()
        start_frame = RLPy.GetFrameIndex(RLPy.RGlobal.GetStartTime(), fps)
        end_frame = RLPy.GetFrameIndex(RLPy.RGlobal.GetEndTime(), fps)
        target_frame = max(start_frame, min(self.saved_frame_number, end_frame))
        
        target_time = RLPy.IndexedFrameTime(target_frame, fps)
        RLPy.RGlobal.SetTime(target_time)
        print(f"[Wanderer] Returned to frame {target_frame}.")


# === UI INITIALIZATION AND INTEGRATION ===
main_window = None
try:
    for widget in QApplication.topLevelWidgets():
        if widget.objectName() == "MainWindow" or "iClone" in widget.windowTitle():
            main_window = widget
            break
except:
    pass

# Close existing instance to avoid duplicates
global wanderer_ui
try:
    wanderer_ui.close()
    wanderer_ui.deleteLater()
except:
    pass

# Create widget and set parent to iClone to close automatically when iClone exits
wanderer_ui = FrameWandererWidget()

if main_window:
    wanderer_ui.setParent(main_window)
    wanderer_ui.setWindowFlags(Qt.Tool | Qt.WindowStaysOnTopHint)

wanderer_ui.setWindowTitle("Timeline Wanderer")
wanderer_ui.show()