#!/usr/bin/python3
import gi, uuid
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Pango

class App(Gtk.Window):
    def __init__(self):
        super().__init__(title='UUID Generator')
        self.set_default_size(520, 400)
        self.history = []
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
        vbox.set_margin_top(12); vbox.set_margin_bottom(12)
        vbox.set_margin_start(12); vbox.set_margin_end(12)
        self.add(vbox)
        hb = Gtk.Box(spacing=8)
        gen_btn = Gtk.Button(label='Generate UUID v4')
        gen_btn.connect('clicked', self.generate_one)
        hb.pack_start(gen_btn, True, True, 0)
        copy_btn = Gtk.Button(label='Copy')
        copy_btn.connect('clicked', self.copy_current)
        hb.pack_start(copy_btn, False, False, 0)
        vbox.pack_start(hb, False, False, 0)
        self.current = Gtk.Entry(); self.current.set_editable(False)
        self.current.override_font(Pango.FontDescription('Monospace 14'))
        vbox.pack_start(self.current, False, False, 0)
        # batch
        hb2 = Gtk.Box(spacing=8)
        hb2.add(Gtk.Label(label='Batch generate:'))
        self.count_spin = Gtk.SpinButton.new_with_range(1, 100, 1)
        self.count_spin.set_value(5)
        hb2.pack_start(self.count_spin, False, False, 0)
        batch_btn = Gtk.Button(label='Generate N UUIDs')
        batch_btn.connect('clicked', self.generate_batch)
        hb2.pack_start(batch_btn, False, False, 0)
        vbox.pack_start(hb2, False, False, 0)
        vbox.add(Gtk.Label(label='History (last 20):', xalign=0))
        sw = Gtk.ScrolledWindow()
        self.store = Gtk.ListStore(str)
        tv = Gtk.TreeView(model=self.store)
        cr = Gtk.CellRendererText(); cr.set_property('font', 'Monospace 10')
        tv.append_column(Gtk.TreeViewColumn('UUID', cr, text=0))
        tv.get_selection().connect('changed', self.on_history_select)
        sw.add(tv)
        vbox.pack_start(sw, True, True, 0)
        self.generate_one()
    def generate_one(self, *_):
        u = str(uuid.uuid4())
        self.current.set_text(u)
        self._add_to_history(u)
    def generate_batch(self, *_):
        n = int(self.count_spin.get_value())
        uuids = [str(uuid.uuid4()) for _ in range(n)]
        if uuids: self.current.set_text(uuids[0])
        for u in uuids: self._add_to_history(u)
    def _add_to_history(self, u):
        self.history.insert(0, u)
        if len(self.history) > 20: self.history.pop()
        self.store.clear()
        for h in self.history: self.store.append([h])
    def on_history_select(self, sel):
        model, it = sel.get_selected()
        if it: self.current.set_text(model[it][0])
    def copy_current(self, *_):
        clipboard = self.get_clipboard(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(self.current.get_text(), -1)

win = App()
win.connect('destroy', Gtk.main_quit)
win.show_all()
Gtk.main()
