Source: public/javascript/olqv.js

import { velocity2Redshift, redshift2Velocity, getRadiusInDegrees } from "./modules/utils.js";

import { withSAMP, dataPaths, URL_ROOT, header, default_lut_index } from './modules/init.js';
import { SpectroscopyUI, SpectroscopyQuery, SpectroscopyFormatter } from './modules/olqv_spectro.js';
import { FITS_HEADER } from './modules/fitsheader.js';
import { DEFAULT_INTENSITY, DEFAULT_EUP, SPECTRO_COLLECTIONS } from "./modules/constants.js";
//import { DisplayVotable } from "./modules/samp_utils.js";
import { FITSHeaderTable, LicensePanel } from "./modules/page_overlay.js";
import { getViewLinker } from "./modules/olqv_linkedviews.js";
import { CubeSmoother } from "./modules/olqv_smooth.js";
import { SourceTable } from "./modules/olqv_ned.js";
import { MarkerList } from "./modules/olqv_markers.js";
import { getVelocityField, getRedshiftField, showLoaderAction } from "./modules/domelements.js";

let viewLinker;

// list of sources downloaded from NED catalog
let sourceTable;

// samp connection buttons container
let publishSpectrumDiv = $("#publish-spectrum");


// get user input from spectroscopy form
let spectroUI = new SpectroscopyUI();
// perform spectroscopy requests
let spectroq = new SpectroscopyQuery();


// when switching modal display mode
$('#ned-modal').on('show.bs.modal', function(event) {
    let selectRadius = document.getElementById("ned-search-radius");
    let radius = getRadiusInDegrees(selectRadius.options[selectRadius.selectedIndex].value, FITS_HEADER);
    let Hnot = parseFloat(document.getElementById("lines-hnot").value);
    let OmegaM = parseFloat(document.getElementById("lines-omegam").value);
    sourceTable.getSources(header["CRVAL1"], header["CRVAL2"], radius, Hnot, OmegaM);
});

// synchronizes velocity and redshift values when user changes it manually
getVelocityField().addEventListener("keyup", function() {
    const v = getVelocityField().value;
    if (v.trim() !== "") {
        spectroUI.setVelocity(v);
        spectroUI.setRedshift(velocity2Redshift(v));
    } else {
        spectroUI.setVelocity("");
        spectroUI.setRedshift("");
    }
});

getRedshiftField().addEventListener("keyup", function() {
    const z = getRedshiftField().value;
    if (z.trim() !== "") {
        spectroUI.setRedshift(z);
        spectroUI.setVelocity(redshift2Velocity(z));
    } else {
        spectroUI.setRedshift("");
        spectroUI.setVelocity("");
    }

});

/* opens 3D visualization page, deactivated for now
document.getElementById("show-3d-model").addEventListener("click", () => {
    window.open("getYtObj?relFITSFilePath=" + dataPaths.relFITSFilePath +
        "&iRA0=" + viewLinker.summedSlicesImage.ROI.iRA0 + "&iRA1=" + viewLinker.summedSlicesImage.ROI.iRA1 +
        "&iDEC0=" + viewLinker.summedSlicesImage.ROI.iDEC0 + "&iDEC1=" + viewLinker.summedSlicesImage.ROI.iDEC1 +
        "&iFREQ0=" + viewLinker.summedSlicesImage.ROI.iFREQ0 + "&iFREQ1=" + viewLinker.summedSlicesImage.ROI.iFREQ1);
    return false;
});
*/

/**
 *  Removes the selected box on the summedslice viewer when user push X key on keyboard
 *
 * @param {Event} evt
 */
var deleteFeature = function(evt) {
    console.log("var deleteFeature = function(evt){ : entering");
    if (evt.keyCode == 88) {
        viewLinker.forgetSelectedBox();
    }
    console.log("var deleteFeature = function(evt){ : exiting");
};


function changeDatabase(spectroq, spectroUI, dbname) {
    spectroq.getMetadata(function(metadata) { spectroUI.initSpeciesSelection(dbname, metadata) });
    document.getElementById("intensity").value = DEFAULT_INTENSITY;
    document.getElementById("intensityrange").value = DEFAULT_INTENSITY;
}

/**
 * Changes list of spectral lines displayed in table next to the spectrum.
 * Only a few lines are displayed at a time to avoid list becoming too long.
 *
 * @param {int} newGroupIndex index of displayed lines group
 */
function changeLinesGroup(newGroupIndex) {
    spectroUI.changeGroupAction(newGroupIndex, () => {
        viewLinker.summedPixelsSpectrumViewer.linePlotter.plotTransitionGroup(newGroupIndex);
        spectroUI.showEnergyGroupLines(viewLinker.summedPixelsSpectrumViewer.linePlotter.transitionGroups[newGroupIndex]);
    });
}


$(document).ready(function() {
    console.log("$( document ).ready(function() {: entering");

    // Set up everything required to fill and display the FITS header.
    let FITSHDR = new FITSHeaderTable(document.getElementById("fitshdr"), header);
    //Software licenses
    let Licences = new LicensePanel(document.getElementById("licences"));

    // local db is selected by default for spectroscopy
    spectroUI.setDefaultDatabase();
    // fill species autocomplete accordingly
    spectroq.getMetadata(function(metadata) { spectroUI.initSpeciesSelection("local", metadata) });
    spectroUI.disable();
    // by default spectro UI checkbox is hidden
    spectroUI.hideToggler();
    // check that there are lines in spectro db
    // UI remains hidden if nothing is found
    spectroq.getStatuses(spectroUI.toggleDatabaseSelector);

    // remove box selection in slice viewer
    document.addEventListener('keydown', deleteFeature, false);
    $('#LUT-selector').prop('selectedIndex', default_lut_index);

    // set default values for z and spectroscopy
    spectroUI.clearRedshift();
    spectroUI.clearVelocity();
    spectroUI.setIntensity(DEFAULT_INTENSITY);
    spectroUI.setEnergyUp(DEFAULT_EUP);

    showLoaderAction(true);

    $("#spectroscopy-menu").className = "hidden";
    $("#toggle-lines-search").checked = false;

    // hide/show spectroscopy search form
    $("#toggle-lines-search").on("click", function() {
        if (document.getElementById("toggle-lines-search").checked) {
            spectroUI.showSpectroscopyMenu();
        } else {
            spectroUI.hideSpectroscopyMenu();
        }
    });

    // buttons to navigate list of spectral lines
    $("#goto-previous-group").on("click", () => {
        changeLinesGroup(spectroUI.currentGroup - 1);
    });

    $("#goto-next-group").on("click", () => {
        changeLinesGroup(spectroUI.currentGroup + 1);
    });

    $("#goto-last-group").on("click", () => {
        changeLinesGroup(viewLinker.summedPixelsSpectrumViewer.linePlotter.transitionGroups.length - 1);
    });

    $("#goto-first-group").on("click", () => {
        changeLinesGroup(0);
    });

    // user select a datasource
    $("#localdatasource").on("click", function() {
        spectroUI.disable();
        spectroq.getMetadata(function(metadata) { spectroUI.initSpeciesSelection("local", metadata) });
        changeDatabase(spectroq, spectroUI, SPECTRO_COLLECTIONS.local);
    });

    $("#ismdatasource").on("click", function() {
        spectroUI.enable();
        changeDatabase(spectroq, spectroUI, SPECTRO_COLLECTIONS.ism);
    });

    $("#ismcsmdatasource").on("click", function() {
        spectroUI.enable();
        changeDatabase(spectroq, spectroUI, SPECTRO_COLLECTIONS.ismcsm);
    });

    $("#jpldatasource").on("click", function() {
        spectroUI.enable();
        changeDatabase(spectroq, spectroUI, SPECTRO_COLLECTIONS.jpl);
    });

    $("#cdmsdatasource").on("click", function() {
        spectroUI.enable();
        changeDatabase(spectroq, spectroUI, SPECTRO_COLLECTIONS.cdms);
    });

    // user wants to display all lines for a dataset
    document.getElementById("selectedspecies").addEventListener("getdataset", (event) => {
        spectroq.getDataset(event.detail.db, event.detail.dataset, (result) => {

            const obsFreqMin = viewLinker.summedPixelsSpectrumViewer.summedPixelsSpectrumChart.obsFreqMin;
            const obsFreqMax = viewLinker.summedPixelsSpectrumViewer.summedPixelsSpectrumChart.obsFreqMax;

            if (event.detail.db !== SPECTRO_COLLECTIONS.local) {
                let shift = spectroUI.getShift();
                const formatter = new SpectroscopyFormatter();
                const content = formatter.linesTofile(result, shift["shiftValue"], shift["shiftType"], obsFreqMin, obsFreqMax);
                document.getElementById("spetro-modal-lines").innerText = content;
                $('#spectro-modal').modal('show');
            } else {
                alert("Not available for local database");
            }

        })
    });


    $("#spectrum-info-title").html(FITS_HEADER.getSpectrumTitle());
    $("#cube-infos").html(FITS_HEADER.getFitsSummary());

    $('#show-fits-header').click(function() {
        FITSHDR.show()
    });

    $('#show-license').click(function() {
        Licences.show()
    });

    // zoom buttons for both spectra
    $("#zoom-in").on('click', function() {
        let factor = Math.abs((viewLinker.spectrumViewer.spectrumChart.xAxis[0].min - viewLinker.spectrumViewer.spectrumChart.xAxis[0].max) * 0.2);
        let minVal = viewLinker.spectrumViewer.spectrumChart.xAxis[0].min + factor;
        let maxVal = viewLinker.spectrumViewer.spectrumChart.xAxis[0].max - factor;
        viewLinker.spectrumViewer.spectrumChart.xAxis[0].setExtremes(minVal, maxVal);
    });

    $("#zoom-out").on('click', function() {
        let factor = Math.abs((viewLinker.spectrumViewer.spectrumChart.xAxis[0].min - viewLinker.spectrumViewer.spectrumChart.xAxis[0].max) * 0.2);
        let minVal = viewLinker.spectrumViewer.spectrumChart.xAxis[0].min - factor;
        let maxVal = viewLinker.spectrumViewer.spectrumChart.xAxis[0].max + factor;
        viewLinker.spectrumViewer.spectrumChart.xAxis[0].setExtremes(minVal, maxVal);
    });

    $("#zoom-reset").on('click', () => {
        viewLinker.spectrumViewer.spectrumChart.xAxis[0].setExtremes(undefined, undefined);
    });

    // checks conformity of number of channels to smooth
    $("#get-nbox").keyup(function() {
        var nbox = $(this).val();
        if (nbox !== "" && isNaN(parseInt(nbox)))
            alert("nbox must be a number");
    });

    $("#get-smooth-cube").on('click', function() {
        showLoaderAction(true);
        let cubeSmoother = new CubeSmoother(viewLinker, dataPaths.relFITSFilePath);
        $.when(cubeSmoother.createSmoothedCube(parseInt($("#get-nbox").val()))).done(function() {
            var url = URL_ROOT + cubeSmoother.getSmoothedCubePath();
            showLoaderAction(false);
            window.open(url, '_blank');
        });
    });
    $("#view-smooth-cube").on('click', function() {
        showLoaderAction(true);
        let cubeSmoother = new CubeSmoother(viewLinker, dataPaths.relFITSFilePath);
        $.when(cubeSmoother.createSmoothedCube(parseInt($("#get-nbox").val()))).done(function() {
            var url = URL_ROOT + "/visit/?relFITSFilePath=//SMOOTH" + cubeSmoother.getSmoothedCubePath();
            showLoaderAction(false);
            window.open(url);
        });
    });

    $("#slice").on('mouseenter', function() {
        viewLinker.singleSliceImage._map_controls.forEach(function(ctrl) {
            viewLinker.singleSliceImage._map.addControl(ctrl);
        });
    });

    $("#slice").on('mouseleave', function() {
        viewLinker.singleSliceImage._map_controls.forEach(function(ctrl) {
            viewLinker.singleSliceImage._map.removeControl(ctrl);
        });
    });

    $("#summed-slices").on("mouseenter", function() {
        viewLinker.summedSlicesImage._map_controls.forEach(function(ctrl) {
            viewLinker.summedSlicesImage._map.addControl(ctrl);
        });
    });

    $("#summed-slices").on("mouseleave", function() {
        viewLinker.summedSlicesImage._map_controls.forEach(function(ctrl) {
            viewLinker.summedSlicesImage._map.removeControl(ctrl);
        });
    });


    // Shows SAMP connector logo if SAMP is activated
    if (!withSAMP) {
        $(publishSpectrumDiv).css("display", "none");
        $('#samp-img').css("display", "none");
    }

    /**
        Get RA/DEC ranges corresponding to opened fits file
        response format is a pair of pairs of float values `[[ra0, dec0], [ra1, dec1], [ra2, dec2]]`
        expressing angles in decimal degrees where :

        * `ra0` corresponds to the index 0 along the RA axis.
        * `ra1` corresponds to the index NAXIS1-1 along the RA axis.
        * `dec0` corresponds to the index 0 along the DEC axis.
        * `dec1` corresponds to the index NAXIS2-1 along the DEC axis.
        * `ra2` corresponds to the index max(NAXIS1, NAXIS2)-1 along the RA axis.
        * `dec2` corresponds to the index max(NAXIS1, NAXIS2)-1 along the DEC axis.
    */
    $.post("", {
        "method": "RADECRangeInDegrees",
        "relFITSFilePath": dataPaths.relFITSFilePath,
        "sessionID": 0
    }).done(function(resp) {
        console.log('$.post("", {"method": "RADECRangeInDegrees", "relFITSFilePath": dataPaths.relFITSFilePath}).done(function (resp) { : entering');

        let markerList = new MarkerList("input-markers", "show-markers", "clear-markers");
        //ned data selection
        sourceTable = new SourceTable('ned-data', 'ned-modal-title', spectroUI);
        sourceTable.addListener(markerList);
        viewLinker = getViewLinker(resp.data["result"], spectroUI, sourceTable, markerList);
        $('#rccap').click(function() {
            viewLinker.refresh()
        });
        console.log('$.post("", {"method": "RADECRangeInDegrees", "relFITSFilePath": dataPaths.relFITSFilePath}).done(function(resp) {: exiting');
    });
    console.log("$( document ).ready(function() {: exiting");
});