import gi
import webbrowser
import os

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GdkPixbuf, GLib

ICON_PATH = "/usr/share/icons/hicolor/128x128/apps/"

class ServiceSelection(Gtk.Window):
    def __init__(self):
        super().__init__()
        self.set_border_width(15)
        self.set_default_size(900, 650)
        self.set_resizable(True)
        self.set_title("Seleziona un Servizio")
        self.set_position(Gtk.WindowPosition.CENTER)
        
        self.apply_css()
        
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=40)
        vbox.set_valign(Gtk.Align.CENTER)
        self.add(vbox)
        
        label = Gtk.Label()
        label.set_markup('<span weight="normal" font_family="Audiowide" size="24000" foreground="#E0E0E0">Seleziona un servizio</span>')
        label.set_halign(Gtk.Align.CENTER)
        vbox.pack_start(label, False, False, 0)
        
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=60)
        vbox.set_valign(Gtk.Align.CENTER)
        vbox.pack_start(hbox, False, False, 0)
        
        self.create_service_button(hbox, "UFFICIOZERO LINKS", "ufficiozero", "#FFA07A", "ufficiozero.png")
        self.create_service_button(hbox, "ALTRI LINKS", "altri", "#98FB98", "altri.png")
        
        self.connect("destroy", Gtk.main_quit)
        self.show_all()
    
    def apply_css(self):
        css_provider = Gtk.CssProvider()
        css_provider.load_from_data(b"""
            window {
                background-color: rgba(0, 0, 0, 0.8);
            }
            .fade-out {
                opacity: 0;
                transition: opacity 0.8s ease-in-out;
            }
            .fade-in {
                opacity: 1;
                transition: opacity 0.8s ease-in-out;
            }
        """)
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            css_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )
    
    def create_service_button(self, container, label, service, color, icon_name):
        button = Gtk.Button()
        button_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        button.set_relief(Gtk.ReliefStyle.NONE)
        
        icon_file = os.path.join(ICON_PATH, icon_name)
        if os.path.exists(icon_file):
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(icon_file, 120, 120, True)
            image = Gtk.Image.new_from_pixbuf(pixbuf)
            button_box.pack_start(image, False, False, 5)
        
        button_label = Gtk.Label()
        button_label.set_markup(f'<span weight="bold" font_family="Fira Code" size="20000" foreground="{color}">{label}</span>')
        button_label.set_halign(Gtk.Align.CENTER)
        button_box.pack_start(button_label, False, False, 0)
        
        button.add(button_box)
        button.connect("clicked", self.fade_out_and_launch, service)
        button.set_size_request(220, 180)
        container.pack_start(button, True, True, 0)

    def fade_out_and_launch(self, button, service):
        self.get_style_context().add_class("fade-out")
        GLib.timeout_add(800, self.hide_and_launch, service)

    def hide_and_launch(self, service):
        self.hide()
        servizi(self, service)

    def fade_in(self):
        self.show_all()
        self.get_style_context().add_class("fade-in")


class servizi(Gtk.Window):
    def __init__(self, parent, service):
        super().__init__()
        self.set_border_width(15)
        self.set_default_size(1100, 900)
        self.set_resizable(True)
        self.set_title("Servizi Ufficiozero")
        self.set_position(Gtk.WindowPosition.CENTER)
        
        self.apply_css()
        self.parent = parent
        
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=20)
        self.add(vbox)
        
        header = Gtk.HeaderBar()
        header.set_show_close_button(True)
        header.set_title("Servizi Ufficiozero")
        self.set_titlebar(header)
        
        back_button = Gtk.Button(label="⬅ Torna indietro")
        back_button.connect("clicked", self.fade_out_and_go_back)
        header.pack_start(back_button)
        
        self.links = self.get_links(service)
        self.create_grid_layout(vbox)
        
        self.fade_in()
    
    def apply_css(self):
        css_provider = Gtk.CssProvider()
        css_provider.load_from_data(b"""
            window {
                background-color: rgba(0, 0, 0, 0.85);
            }
        """)
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            css_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

    def fade_out_and_go_back(self, button):
        self.get_style_context().add_class("fade-out")
        GLib.timeout_add(800, self.hide_and_go_back)

    def hide_and_go_back(self):
        self.hide()
        self.parent.fade_in()

    def fade_in(self):
        self.show_all()
        self.get_style_context().add_class("fade-in")

    def open_link(self, button, url):
        webbrowser.open(url)

    def get_links(self, service):
        """ Returns the links based on the selected service. """
        if service == "ufficiozero":
            return {
                # Formato: "Nome": ("URL", "Descrizione", "NomeFileIcona.png")
                "Adegua GDPR": ("https://www.adegua.info/", "Servizi e soluzioni personalizzate di adeguamento alle normative in ambito General Data Protection Regulation.", "Adegua GDPR.png"),
                "Cloud": ("https://www.ufficiozero.org/index.php?alias=servizi-cloud-complementari", "Servizio complementare di cloud", "Cloud.png"),
                "Condividimi": ("https://www.condividimi.eu/", "E'' uno strumento ideato e pensato per privati e PMI che vogliono poter condividere file, documenti, immagini ecc. tra colleghi di lavoro, vari team in modo semplice e veloce", "Condividimi.png"),
                "Forum": ("https://forum.ufficiozero.org/", "Forum ufficiale di Ufficiozero", "Forum.png"),
                "Sito": ("https://www.ufficiozero.org/", "Sito principale di Ufficiozero", "Sito.png"),
                "Store SIITE": ("https://store.siite.it/", "Store ufficiale di Ufficiozero", "Store SIITE.png"),
                "Wiki": ("https://wiki.ufficiozero.org/doku.php", "Wiki di Ufficiozero, dove trovare informazioni, soluzioni e trucchi utili", "Wiki.png"),
                "FineMacos": ("https://finemacos.it/", "Campagna promossa da Boost Media APS.", "FineMacos.png"),
                "FineWin10": ("https://finewin10.it/", "Campagna promossa da Boost Media APS.", "FineWin10.png"),
            }
        elif service == "altri":
            return {
                # Formato: "Nome": ("URL", "Descrizione", "NomeFileIcona.png")
                "Amministrativoit": ("https://amministrativo.it/gu/", "Ricerca attraverso parole chiave sula Gazzetta Ufficiale", "Amministrativoit.png"),
                "IncastroPc": ("https://incastropc.com/", "E-Commerce minipc UfficioZero powered!", "incastropc.png"),
                "Jitsi Meet": ("https://meet.jit.si/", "Riunioni sicure e di alta qualità", "Jitsi Meet.png"),
            }
        return {}

    def create_grid_layout(self, parent_vbox):
        grid = Gtk.Grid()
        grid.set_row_spacing(30)
        grid.set_column_spacing(30)
        grid.set_halign(Gtk.Align.BASELINE)
        grid.set_valign(Gtk.Align.BASELINE)
        parent_vbox.pack_start(grid, True, True, 0)
        
        icon_size = 120
        cols = 6
        row, col = 0, 0
        
        for name, (url, description, icon_name) in self.links.items():
            box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
            button = Gtk.Button()
            button.set_relief(Gtk.ReliefStyle.NONE)
            button.set_size_request(icon_size, icon_size)
            
            icon_file = os.path.join(ICON_PATH, icon_name)
            if os.path.exists(icon_file):
                pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(icon_file, icon_size, icon_size, True)
                image = Gtk.Image.new_from_pixbuf(pixbuf)
                button.set_image(image)
            else:
                button.set_label(name)
            
            button.set_tooltip_text(f"{name}: {description}")
            button.connect("clicked", self.open_link, url)
            
            label = Gtk.Label()
            label.set_markup(f'<span weight="bold" font_family="Fira Code" size="20000" foreground="#E0E0E0">{name}</span>')
            label.set_halign(Gtk.Align.CENTER)
            
            box.pack_start(button, False, False, 0)
            box.pack_start(label, False, False, 0)
            
            grid.attach(box, col, row, 1, 1)
            col += 1
            if col >= cols:
                col = 0
                row += 1

if __name__ == "__main__":
    app = ServiceSelection()
    Gtk.main()
