# coding: utf-8
# python 2 only

# Copyright (c) 2026 TormachTips.com. All rights reserved.
# Licensed under the TormachTips Personal Use License.
# Permission is granted only for private personal use and private personal modification.
# No sharing, publication, distribution, resale, sublicensing, screenshots, code excerpts,
# benchmarks, or videos are permitted without prior written permission.
# Requests:         tormach.1100m@gmail.com
# Information page: https://tormachtips.com/plugins.htm

#############################################
##                                         ##
##       Spindle Timer Popup v0.95         ##
##          www.tormachtips.com            ##
##                                         ##
#############################################

# 0.95 - public beta - 4/2/26

# SIMPLE POPUP SHOWING SPINDLE TOTAL TIME AND NOTHING ELSE.
# CAN RUN FROM TERMINAL OR "ADMIN HOBBS" FROM MDI LINE

import re
import os
import Tkinter as tk

HOBBS_FILE  = "/home/operator/gcode/python/hobbs/hobbs.txt"
CURRENT_VER = "0.95"
SCRIPT_NAME = "Hobbs Simple Spindle Time Box"
DESCRIPTION = "A simple popup box of the total spindle hobbs time."

def read_total_seconds(path):
    if not os.path.isfile(path):
        raise IOError("File not found: %s" % path)
    with open(path, "r") as f:
        content = f.read()
    match = re.search(r'^\s*total_seconds\s*=\s*(\d+)\s*$', content, re.MULTILINE)
    if not match:
        raise ValueError("Could not find total_seconds=... in %s" % path)
    return int(match.group(1))

def center_window(root, width, height):
    root.update_idletasks()
    screen_w = root.winfo_screenwidth()
    screen_h = root.winfo_screenheight()
    x = (screen_w - width) / 2
    y = (screen_h - height) / 2
    root.geometry("%dx%d+%d+%d" % (width, height, x, y))

def make_link_label(parent, text, url):
    label = tk.Label(
        parent,
        text=text,
        font=("Arial", 9, "underline"),
        fg="#1d4ed8",
        bg=parent.cget("bg"),
        cursor="hand2"    )
    label.bind("<Button-1>", lambda e: os.system('xdg-open "%s" >/dev/null 2>&1 &' % url))
    return label

def main():
    def format_runtime(total_seconds):
        minutes = total_seconds // 60
        seconds = total_seconds % 60
        hours = minutes // 60
        minutes = minutes % 60
        days = hours // 24
        hours = hours % 24
        base_text = "%dh %dm %ds" % (days * 24 + hours, minutes, seconds)
        if days > 0:
            full_text = "(%dd %dh %dm %ds)" % (days, hours, minutes, seconds)
            return "%s\n%s" % (base_text, full_text)
        return base_text
    try:
        total_seconds = read_total_seconds(HOBBS_FILE)
        runtime_text = format_runtime(total_seconds)
        is_error = False
        error_text = ""
    except Exception as e:
        runtime_text = "ERROR"
        error_text = str(e)
        is_error = True
    root = tk.Tk()
    root.title("Tormach Tips - Hobbs Timer")
    root.resizable(False, False)
    root.attributes("-topmost", True)
    root.configure(bg="#e5e7eb")
    panel = tk.Frame(root, bg="#f8fafc", bd=1, relief="solid")
    panel.pack(fill="both", expand=True, padx=10, pady=10)
    header = tk.Frame(panel, bg="#1f2937", height=42)
    header.pack(fill="x")
    header.pack_propagate(False)
    title = tk.Label(
        header,
        text="Spindle Hobbs Runtime",
        font=("Arial", 13, "bold"),
        fg="white",
        bg="#1f2937"
    )
    title.pack(side="left", padx=12, pady=10)
    body = tk.Frame(panel, bg="#f8fafc")
    body.pack(fill="both", expand=True, padx=18, pady=16)
    value_label = tk.Label(
        body,
        text=runtime_text,
        font=("Arial", 24, "bold"),
        fg="#111827" if not is_error else "#b91c1c",
        bg="#f8fafc",
        justify="center"
    )
    value_label.pack(pady=(4, 12))
    if is_error:
        error_label = tk.Label(
            body,
            text=error_text,
            font=("Arial", 9),
            fg="#b91c1c",
            bg="#f8fafc",
            wraplength=600,
            justify="center"
        )
        error_label.pack(pady=(0, 10))
    site_label = make_link_label(body, "www.tormachtips.com", "https://www.tormachtips.com")
    site_label.pack(pady=(0, 14))
    ok_button = tk.Button(
        body,
        text="Close",
        font=("Arial", 10),
        relief="raised",
        bd=2,
        padx=18,
        pady=8,
        command=root.destroy
    )
    ok_button.pack(pady=(0, 4))
    root.bind("<Escape>", lambda event: root.destroy())
    root.bind("<Return>", lambda event: root.destroy())
    root.bind("<KP_Enter>", lambda event: root.destroy())    
    root.update_idletasks()
    width = root.winfo_reqwidth() * 2
    height = root.winfo_reqheight()
    center_window(root, width, height)
    root.lift()
    def keep_on_top():
        try:
            root.attributes("-topmost", True)
            root.after(2000, keep_on_top)
        except:
            pass
    keep_on_top()
    root.mainloop()

if __name__ == "__main__":
    main()
