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, "DEVOL LINKS", "devol", "#FFA07A", "devol.png")
        self.create_service_button(hbox, "INFOMANIAK LINKS", "infomaniak", "#98FB98", "infomaniak.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()
        AggregatoreDevol(self, service)

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


class AggregatoreDevol(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("AggregatoreDevol")
        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("AggregatoreDevol")
        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 == "devol":
            return {
                "Cryptpad": ("https://cryptpad.devol.it/", "Suite collaborativa cifrata"),
                "Etherpad": ("https://etherpadmypads.devol.it", "Editor collaborativo online"),
                "Mastodon": ("https://mastodon.uno/", "Social network decentralizzato"),
                "PeerTube": ("https://peertube.uno/", "Piattaforma video federata"),
                "Pixelfed": ("https://pixelfed.uno/", "Alternativa federata a Instagram"),
                "Castopod": ("https://castopod.it/", "Podcast federato"),
                "Diggita": ("https://diggita.com/", "Ispirato a digg e reddit è un sito di Giornalismo partecipativo italiano dove aggregare notizie e video"),
                "Funkwhale": ("https://funkwhale.it", "Streaming musicale federato"),
                "Linkstack": ("https://l.devol.it", "Gestione link personali"),
                "Mobilizon": ("https://mobilizon.it", "Eventi e gruppi decentralizzati"),
                "Noblogo": ("https://noblogo.org/about", "Piattaforma di blogging federata"),
                "Nostream": ("https://nostream.mastodon.uno", "Dirette live streaming"),
                "Opensondage": ("https://opensondage.devol.it", "Sondaggi decentralizzati"),
                "PairDrop": ("https://pairdrop.devol.it", "Condivisione file locale"),
                "PrivateBin": ("https://privatebin.devol.it", "Note crittografate anonime"),
                "Vaultwarden": ("https://vaultwarden.devol.it/#/login", "Gestore password self-hosted"),
                "BookWyrm": ("https://bookwyrm.it/", "Social network per lettori"),
            }
        elif service == "infomaniak":
            return {
                "KMail": ("https://mail.infomaniak.com/", "Posta elettronica personale cifrata"),
                "kChat": ("https://kchat.infomaniak.com/", "La soluzione di messaggistica istantanea e sicura concepita per le imprese"),
                "kDrive": ("https://kdrive.infomaniak.com/", "Archivia, condividi e sincronizza i tuoi dati in un cloud etico"),
                "SwissTransfer": ("https://www.swisstransfer.com/it-it", "Invia gratuitamente file fino a 50GB"),
                "kMeet": ("https://kmeet.infomaniak.com/", "Soluzione di videoconferenza sicura, etica, illimitata e gratuita"),
                "kPaste": ("https://kpaste.infomaniak.com/", "Invio sicuro di password, credenziali, numeri di serie o informazioni sensibili."),
                "Chk": ("https://chk.infomaniak.com/", "Crea link brevi e codici QR."),
            }
        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) 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, f"{name.lower()}.png")
            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()

