Source: public/javascript/modules/serverApi.js


import { DOMAccessor } from "./domelements.js";
import { FITS_HEADER } from './fitsheader.js';
import { URL_SPECTRO_SERVER } from './init.js';


/**
 * Object querying the spectroscopy service
 */
 class SpectroApi {
    constructor() {
        // service endpoint
        this.server = URL_SPECTRO_SERVER;
        // will contain result of getMetadata for caching
        this.metadata = null;
        this.getTransitions = this.getTransitions.bind(this);
        this.getMetadata = this.getMetadata.bind(this);
    }

    /**
     * Get a list of transitions
     * @param {string} db           selected database
     * @param {array} frequencies   min/max frequencies
     * @param {array} atomcount     min/max number of atoms
     * @param {number} energyup      maximum value of upper energy (float)
     * @param {array} species       list of species
     * @param {number} intensity     maximum intensity value (float)
     * @param {function} callback   callback function called on found transitions
     */
    getTransitions(db, frequencies, atomcount, energyup, species, intensity, callback) {
        let criteria = {
            "frequencies": frequencies,
            "atomcount": atomcount,
            "energyup": energyup,
            "species": species,
            "idealisedintensity": intensity,
            "sourcefiles": undefined
        };
        $.ajax({
            method: "POST",
            url: this.server + "/spectroscopy/" + db + "/lines",
            data: JSON.stringify(criteria),
            contentType: "application/json",
            crossDomain: true
        })
            .done(function (transitions) {
                callback(transitions);
            }).fail(function (jqXHR, textStatus) {
                console.log("error");
                console.log(jqXHR);
            });
    }

    /**
     * Get a complete dataset with all its transitions
     * @param {string} db            name of selected database
     * @param {string} sourcefile    data file name in source database
     * @param {function} callback      callback function called on returned transitions
     */
    getDataset(db, sourcefile, callback) {
        let criteria = {
            "sourcefile": sourcefile
        };
        $.ajax({
            method: "POST",
            url: this.server + "/spectroscopy/" + db + "/dataset",
            data: JSON.stringify(criteria),
            contentType: "application/json",
            /*crossDomain : true*/
        })
            .done(function (transitions) {
                callback(transitions);
            }).fail(function (jqXHR, textStatus) {
                console.log("error");
                console.log(jqXHR);
            });
    }

    /**
     * Get metadata from spectroscopy database ( species by source database )
     * @param {function} callback function applied to returned data
     */
    getMetadata(callback) {
        let self = this;
        // no ajax request if metadata already available
        if (this.metadata === null) {
            $.ajax({
                method: "GET",
                url: this.server + "/metadata",
                contentType: "application/json",
                /*crossDomain : true*/
            })
                .done(function (metadata) {
                    self.metadata = metadata;
                    callback(metadata);
                }).fail(function (jqXHR, textStatus) {
                    console.log("error");
                    console.log(jqXHR);
                });
        }
        // performs callback on cached data
        else {
            callback(this.metadata);
        }
    }

    /**
     * Get status of dbs from spectroscopy database
     * @param {function} callback function applied to returned data
     */
    getStatuses(callback) {
        // no ajax request if metadata already available
        if (this.metadata === null) {
            $.ajax({
                method: "GET",
                url: this.server + "/spectroscopy/databases/status",
                contentType: "application/json",
                /*crossDomain : true*/
            })
                .done(function (results) {
                    callback(results);
                }).fail(function (jqXHR, textStatus) {
                    console.log("error");
                    console.log(jqXHR);
                });
        }
        // performs callback on cached data
        else {
            callback(this.metadata);
        }
    }

}

/**
 * Access to Yafitss service
 */
 class ServerApi{

    getRADECRangeInDegrees(relFITSFilePath, processResult){
        //DOMAccessor.showLoaderAction(true);
        return $.post("", {
            "method": "RADECRangeInDegrees",
            "relFITSFilePath": relFITSFilePath,
            "sessionID": 0
        }).done(function(resp) {
            console.log('$.post("", {"method": "RADECRangeInDegrees", "relFITSFilePath": dataPaths.relFITSFilePath}).done(function (resp) { : entering');
            processResult(resp);
            //DOMAccessor.showLoaderAction(false);
            console.log('$.post("", {"method": "RADECRangeInDegrees", "relFITSFilePath": dataPaths.relFITSFilePath}).done(function(resp) {: exiting');
        });
    }

    getPixelValue(relFITSFilePath, iRA, iDEC, processResult){
        DOMAccessor.showLoaderAction(true);
        return $.get("getPixelValueAtiRAiDEC", {relFITSFilePath: relFITSFilePath, iRA: iRA, iDEC : iDEC}).done((resp)=>{
            if (resp["status"] == false) {
                // user probably clicked in an area outside the image, we log but don't show
                console.log(resp["message"]);
            } else {
                processResult(resp);
            }
            DOMAccessor.showLoaderAction(false);
        });
    }

    getPixelFreqValue(relFITSFilePath, iRA, iDEC, iFREQ, processResult){
        DOMAccessor.showLoaderAction(true);
        return $.get("getPixelValueAtiFreqiRAiDEC", {relFITSFilePath: relFITSFilePath, iRA: iRA, iDEC: iDEC, iFREQ: iFREQ}).done((resp)=>{
            if (resp["status"] == false) {
                // user probably clicked in an area outside the image, we log but don't show
                console.log(resp["message"]);
            } else {
                processResult(resp);
            }
            DOMAccessor.showLoaderAction(false);
        });
    }

    getSingleSpectrum(iRA, iDEC, relFITSFilePath, processResult){
        // get spectrum
        return $.post("", {
            "method": "getSpectrum",
            "relFITSFilePath": relFITSFilePath,
            "iRA": iRA,
            "iDEC": iDEC,
            "iFREQ0": 0,
            "iFREQ1": FITS_HEADER.naxis3 - 1
        }, null, "json").done(
            /*
             ** This is the function which actually performs the plot as a callback on
             ** return from a call to the FITS file server in order to get the spectrum to draw.
             */
            (resp) => {
                if (resp.data["status"] == false) {
                    // an error occurred
                    if (resp.data["message"] !== "IndexError") {
                        console.log("getSpectrum callback error : " + resp.data["message"]);
                        alert(resp.data["message"]);
                        return;
                    }
                    // there was nothing at given corrdinates
                    else {
                        console.log("getSpectrum callback error : nothing at given coordinates");
                        return;
                    }
                }
                processResult(resp);
                DOMAccessor.showLoaderAction(false);
            }
        ).fail(function(jqXHR, textStatus, errorThrown){
            console.log(errorThrown);
            DOMAccessor.markLoadingDone();
    });
    }

    getSummedSpectrum(iRA0, iRA1, iDEC0, iDEC1, relFITSFilePath, processResult){
        DOMAccessor.showLoaderAction(true);
        return $.post("", {
            "method": "getAverageSpectrum",
            "relFITSFilePath": relFITSFilePath,
            "iRA0": iRA0,
            "iRA1": iRA1,
            "iDEC0": iDEC0,
            "iDEC1": iDEC1
        }).done((resp) => {
            if (resp["status"] == false) {
                alert(`Something went wrong with the calculation of the average spectrum. The message was '${resp["message"]}'`);
            } else {
                processResult(resp);
            }
            DOMAccessor.showLoaderAction(false);
        });
    }

    getSingleSlice(sliceIndex, relFITSFilePath, ittName, lutName, vmName, processResult){
        DOMAccessor.showLoaderAction(true);
        return $.post('png', {
            'si': sliceIndex,
            'relFITSFilePath': relFITSFilePath,
            'ittName': ittName,
            'lutName': lutName,
            'vmName': vmName
        }).done(
            function (resp) {
                console.log("$.post('/png', {'si': sliceIndex, 'relFITSFilePath': _relFITSFilePath}).done(: entering");
                if (resp["status"] == false) {
                    alert("Something went wrong during the generation of the image. The message was '" +
                        resp["message"] + "'");
                } else if (resp["result"] === undefined) {
                    alert("No data available in this channel");
                } else {
                    processResult(resp);
                }
                DOMAccessor.showLoaderAction(false);
                console.log("$.post('/png', {'si': sliceIndex, 'path': _path}).done(: exiting");
            }
        )
    }

    getSummedSlice(sliceIndex0, sliceIndex1, relFITSFilePath, ittName, lutName, vmName, processResult){
        DOMAccessor.showLoaderAction(true);
        return $.post('sumpng', {
            'si0': sliceIndex0,
            'si1': sliceIndex1,
            'relFITSFilePath': relFITSFilePath,
            'ittName': ittName,
            'lutName': lutName,
            'vmName': vmName
        }).done(
            function (resp) {
                console.log(` $.post('/sumpng', {'si0': ${sliceIndex0}, 'si1': ${sliceIndex1}, 'relFITSFilePath': ${self._relFITSFilePath}}).done() : entering`);
                console.log("in _updateSummedSlicesWithPOST");

                if (resp["status"] == false) {
                    alert("Something went wrong during the generation of the image. The message was " +
                        resp["message"] + "'");
                } else if (resp["result"] === undefined) {
                    alert("No data available in this channel");
                } else {
                    processResult(resp);
                }

                DOMAccessor.showLoaderAction(false);
                console.log("$.post('/sumpng', {'si0': sliceIndex0, 'si1': sliceIndex1, 'relFITSFilePath': relFITSFilePath}).done() : exiting");
            });
    }

    getSummedSliceValueAtPixel(iRA, iDEC, iFREQ0, iFREQ1, relFITSFilePath, processResult){
        return $.post("", {
            "method": "getAverage",
            "relFITSFilePath": relFITSFilePath,
            "iRA0": iRA,
            "iRA1": iRA,
            "iDEC0": iDEC,
            "iDEC1": iDEC,
            "iFREQ0": iFREQ0,
            "iFREQ1": iFREQ1,
            "retFITS": false
        }).done(
            (resp) => {
                processResult(resp);
            }
        ).fail(
            function (err) {
                var msg = "POST failed" + JSON.stringify(err, 0, 4);
                alert(msg);
            });
    }

    getFITSSliceImage(sliceIndex, relFITSFilePath, processResult){
        return $.post("", {
            "method": "createFITSSliceImage",
            "relFITSFilePath": relFITSFilePath,
            "iFREQ": sliceIndex
            }).done(
                function (resp) {
                    console.log("A FITS file has been created for the upper image.");
                    let x = JSON.parse(resp);
                    if (!x["status"]) {
                        console.log(`Something went wrong during the generation of the image FITS file, the message was
                        ${x["message"]}`);
                        alert(x["message"]);
                        processResult(x);
                    }
                }
            ).fail(
                function (err) {
                    let msg = "POST failed" + JSON.stringify(err, 0, 4);
                    console.log(msg);
                    alert(msg);
                }
            );
    }

    getSummedFITSSliceImage(sliceIndex0, sliceIndex1, relFITSFilePath, processResult){
        return $.post("", {
            "method": "createFITSSumSliceImage",
            "relFITSFilePath": relFITSFilePath,
            "iFREQ0": sliceIndex0,
            "iFREQ1": sliceIndex1
        }).done(
            function (resp) {
                console.log("A FITS file has been created for the bottom image." + resp);
                let x = JSON.parse(resp);
                if (!x["status"]) {
                    console.log(`Something went wrong during the generation of the bottom image FITS file, the message was
                    ${x["message"]}`);
                    alert(x["message"]);
                    processResult(x);
                }
            }
        ).fail(
            function (err) {
                let msg = "POST failed" + JSON.stringify(err, 0, 4);
                console.log(msg);
                alert(msg);
            }
        );
    }

    createFitsFile(iRA, iDEC, relFITSFilePath, processResult){
        return $.post("", {
            "method": "createFits",
            "relFITSFilePath": relFITSFilePath,
            "iRA": iRA,
            "iDEC": iDEC
        })
        .done(
            function (resp) {
                if (resp["status"] !== false) {
                    processResult(resp);
                    //dataPaths.spectrum = x["result"];
                } else {
                    console.log(`Something went wrong during the generation of 
                    the spectrum FITS file, the message was ${resp["message"]}`);
                    alert(resp["message"]);
                }
            }
        )
        .fail(
            function (err) {
                var msg = "POST failed" + JSON.stringify(err, 0, 4);
                console.log(msg);
                alert(msg);
            }
        );
    }

    measureBox(iRA0, iRA1, iDEC0, iDEC1, iFREQ, relFITSFilePath, processResult){
        return $.post("measureBox", {
            'relFITSFilePath': relFITSFilePath,
            'iFREQ': iFREQ,
            'iRA0': iRA0,
            'iRA1': iRA1,
            'iDEC0': iDEC0,
            'iDEC1': iDEC1
        },
            (resp) => {
                DOMAccessor.showLoaderAction(true);
                if (resp["status"] == false) {
                    alert(`Something went wrong with the measurements of the box [[${iRA0}, ${iDEC0}], [${iRA1},${iDEC1}]]. The message was '${resp["message"]}'`);
                }
                else {
                    processResult(resp);
                }
                DOMAccessor.showLoaderAction(false);
            });
    }

    getContours(postParams, processResult){
        return $.post('getContours', postParams,
        (resp) => {
            DOMAccessor.showLoaderAction(false);
            if (resp["status"] == false) {
                reject(`Error 2 : Something went wrong during the generation of the contours. The message was '${resp["message"]}'`);
            }
            else {
                processResult(resp);
            }
        });
    }   
    

    measureContours(iFREQ, contour, level, relFITSFilePath, processResult){
        DOMAccessor.showLoaderAction(true);
        return $.post('measureContour', { 'relFITSFilePath': relFITSFilePath, 'iFREQ': iFREQ, 'contour': contour, 'level': level },
        (resp) => {
            DOMAccessor.showLoaderAction(false);
            processResult(resp);
        });        
    }

    createSmoothCube(nbox, relFITSFilePath, processResult){
        return $.post("", {
            "method": "createSmoothCube",
            "relFITSFilePath": relFITSFilePath,
            "nbox": nbox
        }).done(
            function (resp) {
                console.log("A FITS file has been created for the smoothCube." + resp);
                processResult(resp);
            }
        ).fail(
            function (err) {
                var msg = "POST failed" + JSON.stringify(err, 0, 4);
                console.log(msg);
                alert(msg);
            }
        );
    }
}

export{
    ServerApi,
    SpectroApi
}