# worldtime_v03.py
import os
import sys
from tkinter import Tk, filedialog, messagebox, Toplevel, Label, Entry, Button, StringVar
from moviepy.video.io.VideoFileClip import VideoFileClip
from datetime import datetime, timedelta

SETTINGS_FILE = "last_used.txt"


def save_last_video_path(path):
    try:
        with open(SETTINGS_FILE, 'w') as f:
            f.write(path)
    except Exception:
        pass


def load_last_video_path():
    if os.path.exists(SETTINGS_FILE):
        with open(SETTINGS_FILE, 'r') as f:
            return f.read().strip()
    return ""


def format_srt_time(seconds):
    hrs = int(seconds // 3600)
    mins = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    millis = int((seconds - int(seconds)) * 1000)
    return f"{hrs:02}:{mins:02}:{secs:02},{millis:03}"


def generate_srt(video_path, interval, ref_video_seconds, ref_real_time, output_path):
    clip = VideoFileClip(video_path)
    duration = clip.duration

    srt_lines = []
    count = 1
    current = 0

    delta = timedelta(
        hours=ref_real_time.hour,
        minutes=ref_real_time.minute,
        seconds=ref_real_time.second
    ) - timedelta(seconds=ref_video_seconds)

    while current < duration:
        start_time = format_srt_time(current)
        end_time = format_srt_time(min(current + interval, duration))

        real_world_time = timedelta(seconds=current) + delta
        hours = int(real_world_time.total_seconds() // 3600) % 24
        minutes = int((real_world_time.total_seconds() % 3600) // 60)
        seconds = int(real_world_time.total_seconds() % 60)

        subtitle_text = f"{hours:02}:{minutes:02}:{seconds:02}"

        srt_lines.append(f"{count}")
        srt_lines.append(f"{start_time} --> {end_time}")
        srt_lines.append(subtitle_text)
        srt_lines.append("")
        count += 1
        current += interval

    with open(output_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(srt_lines))

    messagebox.showinfo("Done", f"SRT file saved as:\n{output_path}")


def open_combined_dialog(root):
    dialog = Toplevel(root)
    dialog.title("Subtitle Generator")
    dialog.geometry("420x360")
    dialog.grab_set()

    def on_close():
        print("Dialog closed by user. Exiting...")
        root.destroy()  # Destroys both dialog and root window

    dialog.protocol("WM_DELETE_WINDOW", on_close)  # Bind close button

    video_path_var = StringVar()
    output_path_var = StringVar()

    def browse_video():
        initial_path = load_last_video_path()
        path = filedialog.askopenfilename(
            title="Select MP4 video",
            filetypes=[("MP4 files", "*.mp4")],
            initialdir=os.path.dirname(initial_path) if initial_path else ""
        )
        if path:
            video_path_var.set(path)
            save_last_video_path(path)
            default_srt = os.path.splitext(path)[0] + "_timeofday.srt"
            output_path_var.set(default_srt)

    def browse_output():
        initialfile = os.path.basename(output_path_var.get())
        initialdir = os.path.dirname(output_path_var.get())
        path = filedialog.asksaveasfilename(
            title="Save SRT as...",
            defaultextension=".srt",
            filetypes=[("Subtitle files", "*.srt")],
            initialdir=initialdir,
            initialfile=initialfile
        )
        if path:
            output_path_var.set(path)

    # UI layout
    Label(dialog, text="1. Select video file:").pack(pady=(10, 0))
    Button(dialog, text="Browse Video...", command=browse_video).pack()
    Label(dialog, textvariable=video_path_var, wraplength=400, fg="blue").pack()

    Label(dialog, text="2. Subtitle interval (seconds):").pack(pady=(10, 0))
    interval_entry = Entry(dialog)
    interval_entry.pack()

    Label(dialog, text="3. Event time in video (seconds):").pack(pady=(10, 0))
    ref_video_entry = Entry(dialog)
    ref_video_entry.pack()

    Label(dialog, text="4. Real-world event time (HH:MM:SS):").pack(pady=(10, 0))
    real_time_entry = Entry(dialog)
    real_time_entry.pack()

    Label(dialog, text="5. Save output SRT file as:").pack(pady=(10, 0))
    Button(dialog, text="Change Output...", command=browse_output).pack()
    Label(dialog, textvariable=output_path_var, wraplength=400, fg="green").pack()

    def on_submit():
        try:
            video_path = video_path_var.get()
            if not os.path.isfile(video_path):
                raise ValueError("Please select a valid video file.")
            interval = int(interval_entry.get())
            ref_video = float(ref_video_entry.get())
            real_time = datetime.strptime(real_time_entry.get(), "%H:%M:%S")
            output_path = output_path_var.get()
            if not output_path:
                raise ValueError("Output path is empty.")

            dialog.destroy()
            generate_srt(video_path, interval, ref_video, real_time, output_path)
        except Exception as e:
            messagebox.showerror("Invalid input", str(e))

    Button(dialog, text="Generate SRT", command=on_submit).pack(pady=15)


    def on_close():
        print("Dialog closed by user. Exiting...")
        root.destroy()  # Destroys both dialog and root window

    dialog.protocol("WM_DELETE_WINDOW", on_close)  # Bind close button
    # Cleanly exit the script

def main():
    root = Tk()
    root.withdraw()

    open_combined_dialog(root)
    root.mainloop()


if __name__ == "__main__":
    main()
