#!/usr/bin/env python3
#--------------------------------------------------------------------------------------------------------
# Name: Linux Lite - Lite Widget
# Architecture: amd64
# Author: Jerry Bezencon
# Website: https://www.linuxliteos.com
# Language: Python/GTK4
# Licence: GPLv2
#--------------------------------------------------------------------------------------------------------

import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk, Gdk, Gio, GLib

import gettext as _gt, locale as _loc
TEXTDOMAIN = "lite-widget"
try:
    _loc.setlocale(_loc.LC_ALL, "")
except _loc.Error:
    pass
_gt.bindtextdomain(TEXTDOMAIN, "/usr/share/locale")
_gt.textdomain(TEXTDOMAIN)
_ = _gt.translation(TEXTDOMAIN, "/usr/share/locale", fallback=True).gettext


import subprocess

TOAST_CSS = b"""
.dark-text { color: #1e1e1e; }
.dim-label { opacity: 0.75; }
.toast-notification {
    background: alpha(@theme_fg_color, 0.8);
    color: @theme_bg_color;
    border-radius: 99px;
    padding: 6px 18px;
    margin: 12px;
}
"""


class LiteWidgetWindow(Gtk.ApplicationWindow):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.set_title("Lite Widget")
        self.set_default_size(380, -1)
        self.set_resizable(False)

        self.set_icon_name("lite-widget")

        # Load CSS for toast notifications
        css_provider = Gtk.CssProvider()
        css_provider.load_from_data(TOAST_CSS)
        Gtk.StyleContext.add_provider_for_display(
            Gdk.Display.get_default(),
            css_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
        )

        # Header bar
        header = Gtk.HeaderBar()
        self.set_titlebar(header)

        # Overlay for toast notifications
        self.overlay = Gtk.Overlay()

        self.toast_label = Gtk.Label()
        self.toast_label.add_css_class("toast-notification")
        self.toast_label.set_halign(Gtk.Align.CENTER)
        self.toast_label.set_valign(Gtk.Align.END)
        self.toast_label.set_visible(False)
        self.overlay.add_overlay(self.toast_label)

        # Content
        content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=24)
        content.set_margin_top(24)
        content.set_margin_bottom(24)
        content.set_margin_start(12)
        content.set_margin_end(12)

        # Status group
        status_frame = Gtk.Frame(label=_("Status"))
        status_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        status_box.set_margin_top(6)
        status_box.set_margin_bottom(12)
        status_box.set_margin_start(12)
        status_box.set_margin_end(12)

        status_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        status_row.set_margin_top(6)
        self.status_icon = Gtk.Image()
        self.status_icon.set_pixel_size(16)
        self.status_icon.set_valign(Gtk.Align.CENTER)
        status_labels = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
        status_labels.set_hexpand(True)
        status_title = Gtk.Label(label=_("Widget Status"))
        status_title.set_halign(Gtk.Align.START)
        self.status_subtitle = Gtk.Label()
        self.status_subtitle.set_halign(Gtk.Align.START)
        self.status_subtitle.add_css_class("dim-label")
        status_labels.append(status_title)
        status_labels.append(self.status_subtitle)
        status_row.append(self.status_icon)
        status_row.append(status_labels)
        status_box.append(status_row)
        status_frame.set_child(status_box)

        content.append(status_frame)

        self._update_status()

        # Actions group
        actions_frame = Gtk.Frame(label=_("Actions"))
        actions_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        actions_box.set_margin_top(6)
        actions_box.set_margin_bottom(12)
        actions_box.set_margin_start(12)
        actions_box.set_margin_end(12)

        # Enable row
        enable_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        enable_row.set_margin_top(6)
        enable_labels = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
        enable_labels.set_hexpand(True)
        enable_title = Gtk.Label(label=_("Enable Widget"))
        enable_title.set_halign(Gtk.Align.START)
        enable_subtitle = Gtk.Label(label=_("Start the desktop widget and enable autostart"))
        enable_subtitle.set_halign(Gtk.Align.START)
        enable_subtitle.add_css_class("dim-label")
        enable_labels.append(enable_title)
        enable_labels.append(enable_subtitle)
        enable_btn = Gtk.Button(label=_("Enable"))
        enable_btn.add_css_class("suggested-action")
        enable_btn.set_valign(Gtk.Align.CENTER)
        enable_btn.set_size_request(90, -1)
        enable_btn.connect("clicked", self._on_enable)
        enable_row.append(enable_labels)
        enable_row.append(enable_btn)
        actions_box.append(enable_row)

        actions_box.append(Gtk.Separator())

        # Disable row
        disable_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=12)
        disable_labels = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
        disable_labels.set_hexpand(True)
        disable_title = Gtk.Label(label=_("Disable Widget"))
        disable_title.set_halign(Gtk.Align.START)
        disable_subtitle = Gtk.Label(label=_("Stop the desktop widget and disable autostart"))
        disable_subtitle.set_halign(Gtk.Align.START)
        disable_subtitle.add_css_class("dim-label")
        disable_labels.append(disable_title)
        disable_labels.append(disable_subtitle)
        disable_btn = Gtk.Button(label=_("Disable"))
        disable_btn.add_css_class("destructive-action")
        disable_btn.set_valign(Gtk.Align.CENTER)
        disable_btn.set_size_request(90, -1)
        disable_btn.connect("clicked", self._on_disable)
        disable_row.append(disable_labels)
        disable_row.append(disable_btn)
        actions_box.append(disable_row)

        actions_frame.set_child(actions_box)
        content.append(actions_frame)

        self.overlay.set_child(content)
        self.set_child(self.overlay)

        # Refresh status periodically
        GLib.timeout_add_seconds(2, self._update_status)

    def _is_widget_running(self):
        try:
            result = subprocess.run(
                ['pgrep', '-f', 'lite-widget-overlay'],
                capture_output=True, timeout=5
            )
            return result.returncode == 0
        except Exception:
            return False

    def _update_status(self):
        running = self._is_widget_running()
        if running:
            self.status_subtitle.set_label(_("Running"))
            self.status_icon.set_from_icon_name("emblem-ok-symbolic")
        else:
            self.status_subtitle.set_label(_("Stopped"))
            self.status_icon.set_from_icon_name("media-record-symbolic")
        return True

    def _show_toast(self, message):
        self.toast_label.set_label(message)
        self.toast_label.set_visible(True)
        GLib.timeout_add(3000, self._hide_toast)

    def _hide_toast(self):
        self.toast_label.set_visible(False)
        return False

    def _on_enable(self, button):
        subprocess.Popen(['/usr/bin/lite-widget-e'])
        GLib.timeout_add(1500, self._update_status_once)
        self._show_toast("Lite Widget has been enabled.")

    def _on_disable(self, button):
        subprocess.Popen(['/usr/bin/lite-widget-d'])
        GLib.timeout_add(1500, self._update_status_once)
        self._show_toast("Lite Widget has been disabled.")

    def _update_status_once(self):
        self._update_status()
        return False


class LiteWidgetApp(Gtk.Application):
    def __init__(self):
        super().__init__(
            application_id='com.linuxliteos.litewidget',
            flags=Gio.ApplicationFlags.FLAGS_NONE
        )

    def do_activate(self):
        win = self.props.active_window
        if not win:
            win = LiteWidgetWindow(application=self)
        win.present()


def main():
    app = LiteWidgetApp()
    app.run()


if __name__ == '__main__':
    main()
