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

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):
    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

    srt_output_path = os.path.splitext(video_path)[0] + "_timeofday.srt"
    with open(srt_output_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(srt_lines))

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

def open_input_dialog(root, callback):
    dialog = Toplevel(root)
    dialog.title("Subtitle Parameters")
    dialog.geometry("300x200")
    dialog.grab_set()

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

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

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

    def on_submit():
        try:
            interval = int(interval_entry.get())
            ref_video = float(ref_video_entry.get())
            real_time = datetime.strptime(real_time_entry.get(), "%H:%M:%S")
            dialog.destroy()
            callback(interval, ref_video, real_time)
        except Exception as e:
            messagebox.showerror("Invalid input", str(e))

    Button(dialog, text="OK", command=on_submit).pack(pady=10)

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

    video_path = filedialog.askopenfilename(title="Select MP4 video", filetypes=[("MP4 files", "*.mp4")])
    if not video_path:
        return

    def on_params_entered(interval, ref_video_seconds, ref_real_time):
        generate_srt(video_path, interval, ref_video_seconds, ref_real_time)

    open_input_dialog(root, on_params_entered)
    root.mainloop()

if __name__ == "__main__":
    main()
