Source: public/javascript/modules/samp_utils.js

import { dataPaths, withSAMP, URL_ROOT } from './init.js';
import { displayVotable } from "./votable.js";

/*
 ** A set of classes and function definitions utilized by the
 ** differents flavours of SAMP.
 **
 ** Author : Y. A. BA
 ** Date : 18th September 2019
 */


let samp_registration_area = $('#samp-registration');
let samp_registration_area2D = $('#sampRegistration');

/**
 * Manages connection to samp hub
 * @param {*} connector  samp hub connector
 * @param {*} dataPaths  paths to data file
 */
var SAMPPublisher = function(connector, dataPaths) {
    console.log("SAMPPublisher ctor: entering");
    let _connector = connector;
    let _dataPaths = dataPaths;

    this.sendPNGSlice = function() {
        console.log("var _sendPNGSlice = function(connection) {: entering");
        //var pngUrl = URL_ROOT + "/" + _relSlicePNGPath;
        var pngUrl = URL_ROOT + "/" + _dataPaths.relSlicePNG;
        console.log("About to send this message 'load " + pngUrl + "' to the HUB");
        var msg = new samp.Message("script.aladin.send", {
            "script": "load " + pngUrl
        });
        _connector.connection.notifyAll([msg]);
        console.log("var _sendPNGSlice = function(connection) {: exiting");
    }

    this.sendPNGSummedSlices = function() {
        //_connector.runWithConnection(_sendPNGSummedSlices);
        console.log("var _sendPNGSummedSlices = function(connection) {: entering");
        //var pngUrl = URL_ROOT + "/" + _relSummedSlicesPNGPath;
        var pngUrl = URL_ROOT + "/" + _dataPaths.relSummedSlicesPNG;
        console.log("About to send this message 'load " + pngUrl + "' to the HUB");
        var msg = new samp.Message("script.aladin.send", {
            "script": "load " + pngUrl
        });

        _connector.connection.notifyAll([msg]);
        console.log("var _sendPNGSummedSlices = function(connection) {: exiting");
    }

    this.sendSpectrumToAll = function(spectrumUrl, tableId) {
        console.log("var _sendSpectrum = function(connection) {: entering");
        //var tabUrl = URL_ROOT + _spectrumPath;            
        console.log(`Sending url ${spectrumUrl}`);
        var msg = new samp.Message("table.load.fits", {
            "table-id": tableId,
            "url": spectrumUrl,
            "name": "Artemix"
        });
        _connector.connection.notifyAll([msg]);
        console.log("var _sendSpectrum = function(connection) {: exiting");
    }

    this.setSliceRelPNGPath = function(relSlicePNGPath) {
        _dataPaths.relSlice = relSlicePNGPath;
    };

    console.log("SAMPPublisher ctor: exiting");
}

var sAMPPublisher = undefined;
var setOnHubAvailability = undefined;
var setOnHubAvailability2D = undefined;

if (withSAMP) {
    /*
     ** Set up everything required for the SAMP publisher.
     */
    var cc = new samp.ClientTracker();
    var callHandler = cc.callHandler;
    //let publishSpectrumDiv = $("#publish-spectrum");


    callHandler["samp.app.ping"] = function(senderId, message, isCall) {
        if (isCall) {
            return {
                text: "ping to you, " + cc.getName(senderId)
            };
        }
    };

    //receive a votable
    callHandler["table.load.votable"] = function(senderId, message, isCall) {
        var params = message["samp.params"];
        var origUrl = params["url"];
        var proxyUrl = cc.connection.translateUrl(origUrl);
        var xhr = samp.XmlRpcClient.createXHR();
        xhr.open("GET", proxyUrl);
        xhr.onload = function() {
            var xml = xhr.responseXML;
            if (xml) {
                try {
                    var data = {};
                    data.content = displayVotable(xml);
                    //to complete when the markers will be available in 3D
                } catch (e) {
                    console.log("error " + e);
                }
            } else {
                console.log("No XML response");
            }
        };
        xhr.onerror = function(err) {
            console.log("Error getting table " + origUrl + "\n" +
                "(" + err + ")");
        };
        xhr.send(null);
    };

    var subs = cc.calculateSubscriptions();

    //description on Artemix in the hub
    let descr = "Artemix is an ALMA data mining experiment prototype. " +
        "its aim is to provide astronomers with a webservice " +
        "that enables to quickly explore the ALMA scientific Archive.";
    var meta = {
        "samp.name": "Artemix:" + dataPaths.relFITSFilePath,
        "samp.description": descr
    };
    //connection to the hub
    let connector = new samp.Connector("Artemix", meta, cc, subs);

    /**
     * Enable or disable SAMP in 2D slice
     */
    setOnHubAvailability2D = function(customControls,publishSAMP) {
        samp_registration_area2D.append(connector.createRegButtons());
        let configureSampEnabled = function(isHubRunning) {
            //if the hub is not running or the registration into the hub is not done yet, the samp button will be hidden
            if (!isHubRunning) {
                
            } else {
                if (!connector.connection) {
                    customControls.removeButton(publishSAMP.getButton());
                } else { 
                    customControls.addButton(publishSAMP.getButton());
                }
            }
        };
        connector.onHubAvailability(configureSampEnabled, 3000);
    };
    /**
     * Enable or disable SAMP from a list of viewers
     * @param {*} viewers 
     */

    setOnHubAvailability = function(viewers) {
        samp_registration_area.append(connector.createRegButtons());
        let configureSampEnabled = function(isHubRunning) {
            //if the hub is not running or the registration into the hub is not done yet, the samp button will be hidden
            if (!isHubRunning) {
                //publishSpectrumDiv.css("display", "none");
                //$(".samp-publish-png").css("display", "none");

                //clean console to prevent it from being filled with messages
                //when no hub is available
                //console.clear();
            } else {
                if (!connector.connection) {
                    //publishSpectrumDiv.css("display", "none");
                    //$(".samp-publish-png").css("display", "none");

                    for (let viewer of viewers) {
                        if (viewer !== undefined) {
                            viewer.setSampButtonVisible(false);

                        }
                    }
                } else {
                    //publishSpectrumDiv.css("display", "block");
                    //$(".samp-publish-png").css("display", "block");

                    for (let viewer of viewers) {
                        if (viewer !== undefined) {
                            viewer.setSampButtonVisible(true);

                        }
                    }
                }
            }
        };
        connector.onHubAvailability(configureSampEnabled, 3000);
    };

    window.onbeforeunload = function() {
        connector.unregister();
    };

    sAMPPublisher = new SAMPPublisher(connector, dataPaths);
}

class PublishSAMP {
    constructor(sAMPPublisher) {
        this.publisher = sAMPPublisher;
        this.button = document.createElement("button");
        this.button.setAttribute("type", "button");
        this.button.setAttribute("class", "btn btn-primary btn-sm");
        this.button.setAttribute("data-tooltip", "tooltip");
        this.button.setAttribute("title", "Publish image via a SAMP hub");
        let x = document.createElement("span");
        x.setAttribute("class", "fas fa-location-arrow");
        this.button.appendChild(x);

        $(this.button).on("click", function(event) { sAMPPublisher.sendPNGSlice() });
    }

    getButton() {
        return this.button;
    }
}

export {
    sAMPPublisher,
    setOnHubAvailability,
    setOnHubAvailability2D,
    PublishSAMP
}