# 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

############################################
##                                        ##
##     Tool Life Manager Sub Tag 0.95     ##
##          www.tormachtips.com           ##
##                                        ##
############################################

# 0.95 - Public release.    - 6/07/2026

import os
import subprocess
import gtk
import glib
import pango
import constants
import singletons
from ui_hooks import plugin, version_list

CURRENT_VER          = "0.95"
SCRIPT_NAME          = "Tool Life Offsets Sub Tab"
DESCRIPTION          = "Puts a Sub Tab atop the Tool | Work offsets tab, so you can easily get into the Tool Life Manager"
ENABLED              = 1
DEV_MACHINE          = 1
DEV_MACHINE_FLAG     = "/home/operator/gcode/python/dev_machine.txt"
TOOL_MANAGER_SCRIPT  = "/home/operator/gcode/python/hobbs_db_viewer.py"
PAGE_WIDTH           = 988
PAGE_HEIGHT          = 365
BACKGROUND_COLOR     = "#2b2b2b"

class UserPlugin(plugin):
    def __init__(self):
        plugin.__init__(self, SCRIPT_NAME)
        self._page_widget = None
        dev_machine_found = os.path.exists(DEV_MACHINE_FLAG)
        if dev_machine_found:
            plugin_enabled = DEV_MACHINE
        else:
            plugin_enabled = ENABLED
        if plugin_enabled:
            glib.timeout_add(3000, self.start_process)

    def start_process(self):
        try:
            ui = singletons.g_Machine
            if ui is not None:
                self.add_tool_life_subtab(ui)
        except Exception as e:
            self.error_handler.write("[%s] Startup error: %s" % (SCRIPT_NAME, str(e)), constants.ALARM_LEVEL_LOW)
        return False

    def add_tool_life_subtab(self, ui):
        offsets_notebook = ui.builder.get_object("offsets_notebook")
        if offsets_notebook is None:
            self.error_handler.write("[%s] Could not find offsets_notebook." % SCRIPT_NAME, constants.ALARM_LEVEL_LOW)
            return
        self._page_widget = gtk.Fixed()
        self._page_widget.set_name("tool_life_offsets_fixed")
        self._page_widget.set_size_request(PAGE_WIDTH, PAGE_HEIGHT)
        self.build_page()
        tab_label = gtk.Label("Tool Life Manager")
        offsets_notebook.insert_page(self._page_widget, tab_label, 1)
        offsets_notebook.show_all()

    def get_oem_background_path(self):
        version_str = "v%s.%s.%s" % (version_list[0], version_list[1], version_list[2])
        return os.path.join("/home/operator", version_str, "python", "images", "dark_background.jpg")

    def add_oem_background(self):
        # Match the OEM brushed-steel background used by the runtime tab plugins.
        bg_path = self.get_oem_background_path()
        if os.path.exists(bg_path):
            try:
                pixbuf = gtk.gdk.pixbuf_new_from_file(bg_path)
                scaled = pixbuf.scale_simple(PAGE_WIDTH, PAGE_HEIGHT, gtk.gdk.INTERP_BILINEAR)
                image = gtk.Image()
                image.set_from_pixbuf(scaled)
                self._page_widget.put(image, 0, 0)
                image.show()
                return
            except Exception:
                pass
        try:
            self._page_widget.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(BACKGROUND_COLOR))
        except Exception:
            pass

    def build_page(self):
        self.add_oem_background()
        title = gtk.Label()
        title.set_use_markup(True)
        title.set_markup('<span weight="bold" foreground="white" size="large">Tool Life Manager</span>')
        title.set_alignment(0.0, 0.5)
        self._page_widget.put(title, 35, 30)
        note = gtk.Label()
        note.set_use_markup(True)
        note.set_markup('<span foreground="white" font_desc="Roboto Condensed 11">Tool Life Management requires hobbs_plugin.py and hobbs_db_viewer.py to be installed.\n\nThis button opens the external Tool Life Manager. If either required file is missing, the manager and cutter history features will not work.</span>')
        note.set_alignment(0.0, 0.5)
        self._page_widget.put(note, 35, 65)
        button = gtk.Button("Open Tool Life Manager")
        button.modify_font(pango.FontDescription("Roboto Condensed 12"))
        button.set_size_request(230, 48)
        button.connect("clicked", self.on_open_tool_life_manager)
        self._page_widget.put(button, 35, 145)

    def on_open_tool_life_manager(self, widget):
        try:
            if os.path.isfile(TOOL_MANAGER_SCRIPT):
                subprocess.Popen(["python", TOOL_MANAGER_SCRIPT])
            else:
                self.error_handler.write("[%s] Tool manager not found: %s" % (SCRIPT_NAME, TOOL_MANAGER_SCRIPT), constants.ALARM_LEVEL_LOW)
        except Exception as e:
            self.error_handler.write("[%s] Tool manager launch error: %s" % (SCRIPT_NAME, str(e)), constants.ALARM_LEVEL_LOW)