package ctbrec.ui;

import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.io.File;
import java.io.IOException;
import java.net.URI;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ctbrec.OS;
import ctbrec.io.StreamRedirectThread;
import javafx.geometry.Insets;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;

public class DesktopIntegration {

    private static final transient Logger LOG = LoggerFactory.getLogger(DesktopIntegration.class);

    private static SystemTray tray;
    private static TrayIcon trayIcon;

    public static void open(String uri) {
        try {
            CamrecApplication.hostServices.showDocument(uri);
            return;
        } catch (Exception e) {
            LOG.debug("Couldn't open URL with host services {}", uri);
        }

        // opening with HostServices failed, now try Desktop
        try {
            Desktop.getDesktop().browse(new URI(uri));
            return;
        } catch (Exception e) {
            LOG.debug("Couldn't open URL with Desktop {}", uri);
        }

        // try external helpers
        String[] externalHelpers = {"kde-open5", "kde-open", "gnome-open", "xdg-open"};
        Runtime rt = Runtime.getRuntime();
        for (String helper : externalHelpers) {
            try {
                rt.exec(helper + " " + uri);
                return;
            } catch (IOException e) {
                LOG.debug("Couldn't open URL with {} {}", helper, uri);
            }
        }

        // all attempts failed, show a dialog with URL at least
        Alert info = new AutosizeAlert(Alert.AlertType.ERROR);
        info.setTitle("Open URL");
        info.setContentText("Couldn't open URL");
        BorderPane pane = new BorderPane();
        pane.setTop(new Label());
        TextField urlField = new TextField(uri);
        urlField.setPadding(new Insets(10));
        urlField.setEditable(false);
        pane.setCenter(urlField);
        info.getDialogPane().setExpandableContent(pane);
        info.getDialogPane().setExpanded(true);
        info.show();
    }

    public static void open(File f) {
        try {
            Desktop.getDesktop().open(f);
            return;
        } catch (Exception e) {
            LOG.debug("Couldn't open file with Desktop {}", f);
        }

        // try external helpers
        String[] externalHelpers = {"kde-open5", "kde-open", "gnome-open", "xdg-open"};
        Runtime rt = Runtime.getRuntime();
        for (String helper : externalHelpers) {
            try {
                rt.exec(helper + " " + f.getAbsolutePath());
                return;
            } catch (IOException e) {
                LOG.debug("Couldn't open file with {} {}", helper, f);
            }
        }

        // all attempts failed, show a dialog with path at least
        Alert info = new AutosizeAlert(Alert.AlertType.ERROR);
        info.setTitle("Open file");
        info.setContentText("Couldn't open file");
        BorderPane pane = new BorderPane();
        pane.setTop(new Label());
        TextField urlField = new TextField(f.toString());
        urlField.setPadding(new Insets(10));
        urlField.setEditable(false);
        pane.setCenter(urlField);
        info.getDialogPane().setExpandableContent(pane);
        info.getDialogPane().setExpanded(true);
        info.show();
    }

    public static void notification(String title, String header, String msg) {
        if(OS.getOsType() == OS.TYPE.LINUX) {
            notifyLinux(title, header, msg);
        } else if(OS.getOsType() == OS.TYPE.WINDOWS) {
            notifyWindows(title, header, msg);
        } else if(OS.getOsType() == OS.TYPE.MAC) {
            notifyMac(title, header, msg);
        } else {
            // unknown system, try systemtray notification anyways
            notifySystemTray(title, header, msg);
        }
    }

    private static void notifyLinux(String title, String header, String msg) {
        try {
            Process p = Runtime.getRuntime().exec(new String[] {
                    "notify-send",
                    "-u", "normal",
                    "-t", "5000",
                    "-a", title,
                    header,
                    msg.replaceAll("-", "\\\\-").replaceAll("\\s", "\\\\ "),
                    "--icon=dialog-information"
            });
            new Thread(new StreamRedirectThread(p.getInputStream(), System.out)).start();
            new Thread(new StreamRedirectThread(p.getErrorStream(), System.err)).start();
        } catch (IOException e1) {
            LOG.error("Notification failed", e1);
        }
    }

    private static void notifyWindows(String title, String header, String msg) {
        notifySystemTray(title, header, msg);
    }

    private static void notifyMac(String title, String header, String msg) {
        notifySystemTray(title, header, msg);
    }

    private synchronized static void notifySystemTray(String title, String header, String msg) {
        if(SystemTray.isSupported()) {
            if(tray == null) {
                LOG.debug("Creating tray icon");
                tray = SystemTray.getSystemTray();
                Image image = Toolkit.getDefaultToolkit().createImage(DesktopIntegration.class.getResource("/icon64.png"));
                trayIcon = new TrayIcon(image, title);
                trayIcon.setImageAutoSize(true);
                trayIcon.setToolTip(title);
                try {
                    tray.add(trayIcon);
                } catch (AWTException e) {
                    LOG.error("Coulnd't add tray icon", e);
                }
            }
            LOG.debug("Display tray message");
            trayIcon.displayMessage(header, msg, MessageType.INFO);
        } else {
            LOG.error("SystemTray notifications not supported by this OS");
        }
    }
}
