package org.example.petshopdesktop.util;

import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;

import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.image.BufferedImage;

public class DesktopNotificationService {
    private static final DesktopNotificationService INSTANCE = new DesktopNotificationService();

    private TrayIcon trayIcon;
    private boolean trayInitialized = false;

    private DesktopNotificationService() {}

    public static DesktopNotificationService getInstance() {
        return INSTANCE;
    }

    public void init(Image appIcon) {
        if (!SystemTray.isSupported()) return;
        try {
            BufferedImage image;
            if (appIcon != null) {
                image = SwingFXUtils.fromFXImage(appIcon, null);
            } else {
                image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
            }
            trayIcon = new TrayIcon(image, "Leon's Pet Store");
            trayIcon.setImageAutoSize(true);
            SystemTray.getSystemTray().add(trayIcon);
            trayInitialized = true;
        } catch (Exception ignored) {}
    }

    public void notifyNewMessage(String senderName, String content) {
        Thread t = new Thread(() -> {
            Toolkit.getDefaultToolkit().beep();
            showNotification(senderName, content);
        });
        t.setDaemon(true);
        t.start();
    }

    private void showNotification(String senderName, String content) {
        String title = senderName != null ? senderName : "New Message";
        String body = content != null
                ? (content.length() > 100 ? content.substring(0, 100) + "..." : content)
                : "Attachment";

        if (trayInitialized && trayIcon != null) {
            trayIcon.displayMessage(title, body, TrayIcon.MessageType.INFO);
            return;
        }

        try {
            new ProcessBuilder("notify-send", title, body).start();
        } catch (Exception ignored) {}
    }
}
