<commit_before>/*
 * @author     <NAME> <<EMAIL>>
 * @copyright  2013-2018 MapCentia ApS
 * @license    http://www.gnu.org/licenses/#AGPL  GNU AFFERO GENERAL PUBLIC LICENSE 3
 */

'use strict';

import { LAYER } from './layerTree/constants';
const layerTreeUtils = require('./layerTree/utils');

const LOG = true;

/**
 *
 * @type {*|exports|module.exports}
 */
var backboneEvents, cloud, legend, layers, layerTree, meta;

/**
 *
 * @type {*|exports|module.exports}
 */
var pushState;

let _self = false;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init}}
 */
module.exports = module.exports = {
    set: function (o) {
        cloud = o.cloud;
        legend = o.legend;
        layers = o.layers;
        layerTree = o.layerTree;
        pushState = o.pushState;
        meta = o.meta;
        backboneEvents = o.backboneEvents;

        _self = this;
        return this;
    },

    /**
     * Enables raster tile vector
     * 
     * @param {String}  gc2Id         Layer name (with prefix)
     * @param {Boolean} forceReload   Specifies if the layer reload should be perfromed
     * @param {Boolean} doNotLegend   Specifies if legend should be re-generated
     * @param {Boolean} setupControls Specifies if layerTree controls should be setup
     * 
     * @returns {Promise}
     */
    enableRasterTile: (gc2Id, forceReload, doNotLegend, setupControls) => {
        if (LOG) console.log(`switchLayer: enableRasterTile ${gc2Id}`);

        return new Promise((resolve, reject) => {
            // Only one layer at a time, so using the raster tile layer identifier
            layers.incrementCountLoading(gc2Id);
            layerTree.setSelectorValue(gc2Id, LAYER.RASTER_TILE);
            layers.addLayer(gc2Id, layerTree.getLayerFilterString(gc2Id)).then(() => {
                _self.checkLayerControl(gc2Id, doNotLegend, setupControls);

                let tileLayersCacheBuster = ``;
                if (forceReload) {
                    tileLayersCacheBuster = Math.random();
                }

                // The WMS tile layer and single-tiled at the same time creates the L.nonTiledLayer.wms
                // which does not have the setUrl() method
                let rasterTileLayer = cloud.get().getLayersByName(gc2Id);
                if (`setUrl` in rasterTileLayer) {
                    rasterTileLayer.setUrl(rasterTileLayer._url + "?" + tileLayersCacheBuster);
                    rasterTileLayer.redraw();
                }

                resolve();
            }).catch((err) => {
                meta.init(gc2Id, true, true).then(layerMeta => {
                    // Trying to recreate the layer tree with updated meta and switch layer again                           
                    layerTree.create().then(() => {
                        // All layers are guaranteed to exist in meta
                        let currentLayers = layers.getLayers();
                        if (currentLayers && Array.isArray(currentLayers)) {
                            layers.getLayers().split(',').map(layerToActivate => {
                                _self.checkLayerControl(layerToActivate, doNotLegend, setupControls);
                            });
                        }

                        _self.init(gc2Id, true).then(() => {
                            resolve();
                        });
                    });
                }).catch(() => {
                    console.error(`Could not add ${gc2Id} raster tile layer`);
                    layers.decrementCountLoading(gc2Id);
                    resolve();
                });
            });
        });
    },

    /**
     * Enables vector layer
     * 
     * @param {String}  gc2Id         Layer name (with prefix)
     * @param {Boolean} doNotLegend   Specifies if legend should be re-generated
     * @param {Boolean} setupControls Specifies if layerTree controls should be setup
     * @param {Object}  failedBefore  Specifies if layer loading previously failed (used in recursive init() calling)
     * 
     * @returns {Promise}
     */
    enableVector: (gc2Id, doNotLegend, setupControls, failedBefore) => {
        if (LOG) console.log(`switchLayer: enableVector ${gc2Id}`);

        let vectorLayerId = LAYER.VECTOR + `:` + gc2Id;
        return new Promise((resolve, reject) => {
            try {
            layers.incrementCountLoading(vectorLayerId);
            layerTree.setSelectorValue(name, LAYER.VECTOR);

            let vectorDataStores = layerTree.getStores();
            if (vectorLayerId in vectorDataStores) {
                cloud.get().layerControl.addOverlay(vectorDataStores[vectorLayerId].layer, vectorLayerId);
                let existingLayer = cloud.get().getLayersByName(vectorLayerId);
                cloud.get().map.addLayer(existingLayer);
                vectorDataStores[vectorLayerId].load();

                backboneEvents.get().trigger("startLoading:layers", vectorLayerId);

                _self.checkLayerControl(vectorLayerId, doNotLegend, setupControls);
                resolve();
            } else if (failedBefore !== false) {
                if (failedBefore.reason === `NO_VECTOR_DATA_STORE`) {
                    console.error(`Failed to switch layer while attempting to get the vector data store for ${vectorLayerId} (probably it is not the vector layer)`);
                } else {
                    console.error(`Unknown switch layer failure for ${vectorLayerId}`);
                }

                resolve();
            } else {
                meta.init(rasterTileLayerId, true, true).then(layerMeta => {
                    // Trying to recreate the layer tree with updated meta and switch layer again
                    layerTree.create().then(() => {
                        // All layers are guaranteed to exist in meta
                        let currentLayers = layers.getLayers();
                        if (currentLayers && Array.isArray(currentLayers)) {
                            layers.getLayers().split(',').map(layerToActivate => {
                                _self.checkLayerControl(layerToActivate, doNotLegend, setupControls);
                            });
                        }

                        _self.init(vectorLayerId, true, false, false, true, {
                            reason: `NO_VECTOR_DATA_STORE`
                        }).then(() => {
                            resolve();
                        });
                    });
                }).catch(() => {
                    console.error(`Could not add ${rasterTileLayerId} vector layer`);
                    layers.decrementCountLoading(vectorLayerId);
                    resolve();
                });<commit_msg>Minor fix<commit_after>/*
 * @author     <NAME> <<EMAIL>>
 * @copyright  2013-2018 MapCentia ApS
 * @license    http://www.gnu.org/licenses/#AGPL  GNU AFFERO GENERAL PUBLIC LICENSE 3
 */

'use strict';

import { LAYER } from './layerTree/constants';
const layerTreeUtils = require('./layerTree/utils');

const LOG = true;

/**
 *
 * @type {*|exports|module.exports}
 */
var backboneEvents, cloud, legend, layers, layerTree, meta;

/**
 *
 * @type {*|exports|module.exports}
 */
var pushState;

let _self = false;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init}}
 */
module.exports = module.exports = {
    set: function (o) {
        cloud = o.cloud;
        legend = o.legend;
        layers = o.layers;
        layerTree = o.layerTree;
        pushState = o.pushState;
        meta = o.meta;
        backboneEvents = o.backboneEvents;

        _self = this;
        return this;
    },

    /**
     * Enables raster tile vector
     * 
     * @param {String}  gc2Id         Layer name (with prefix)
     * @param {Boolean} forceReload   Specifies if the layer reload should be perfromed
     * @param {Boolean} doNotLegend   Specifies if legend should be re-generated
     * @param {Boolean} setupControls Specifies if layerTree controls should be setup
     * 
     * @returns {Promise}
     */
    enableRasterTile: (gc2Id, forceReload, doNotLegend, setupControls) => {
        if (LOG) console.log(`switchLayer: enableRasterTile ${gc2Id}`);

        return new Promise((resolve, reject) => {
            // Only one layer at a time, so using the raster tile layer identifier
            layers.incrementCountLoading(gc2Id);
            layerTree.setSelectorValue(gc2Id, LAYER.RASTER_TILE);
            layers.addLayer(gc2Id, layerTree.getLayerFilterString(gc2Id)).then(() => {
                _self.checkLayerControl(gc2Id, doNotLegend, setupControls);

                let tileLayersCacheBuster = ``;
                if (forceReload) {
                    tileLayersCacheBuster = Math.random();
                }

                // The WMS tile layer and single-tiled at the same time creates the L.nonTiledLayer.wms
                // which does not have the setUrl() method
                let rasterTileLayer = cloud.get().getLayersByName(gc2Id);
                if (`setUrl` in rasterTileLayer) {
                    rasterTileLayer.setUrl(rasterTileLayer._url + "?" + tileLayersCacheBuster);
                    rasterTileLayer.redraw();
                }

                resolve();
            }).catch((err) => {
                meta.init(gc2Id, true, true).then(layerMeta => {
                    // Trying to recreate the layer tree with updated meta and switch layer again                           
                    layerTree.create().then(() => {
                        // All layers are guaranteed to exist in meta
                        let currentLayers = layers.getLayers();
                        if (currentLayers && Array.isArray(currentLayers)) {
                            layers.getLayers().split(',').map(layerToActivate => {
                                _self.checkLayerControl(layerToActivate, doNotLegend, setupControls);
                            });
                        }

                        _self.init(gc2Id, true).then(() => {
                            resolve();
                        });
                    });
                }).catch(() => {
                    console.error(`Could not add ${gc2Id} raster tile layer`);
                    layers.decrementCountLoading(gc2Id);
                    resolve();
                });
            });
        });
    },

    /**
     * Enables vector layer
     * 
     * @param {String}  gc2Id         Layer name (with prefix)
     * @param {Boolean} doNotLegend   Specifies if legend should be re-generated
     * @param {Boolean} setupControls Specifies if layerTree controls should be setup
     * @param {Object}  failedBefore  Specifies if layer loading previously failed (used in recursive init() calling)
     * 
     * @returns {Promise}
     */
    enableVector: (gc2Id, doNotLegend, setupControls, failedBefore) => {
        if (LOG) console.log(`switchLayer: enableVector ${gc2Id}`);

        let vectorLayerId = LAYER.VECTOR + `:` + gc2Id;
        return new Promise((resolve, reject) => {
            try {
            layers.incrementCountLoading(vectorLayerId);
            layerTree.setSelectorValue(name, LAYER.VECTOR);

            let vectorDataStores = layerTree.getStores();
            if (vectorLayerId in vectorDataStores) {
                cloud.get().layerControl.addOverlay(vectorDataStores[vectorLayerId].layer, vectorLayerId);
                let existingLayer = cloud.get().getLayersByName(vectorLayerId);
                cloud.get().map.addLayer(existingLayer);
                vectorDataStores[vectorLayerId].load();

                backboneEvents.get().trigger("startLoading:layers", vectorLayerId);

                _self.checkLayerControl(vectorLayerId, doNotLegend, setupControls);
                resolve();
            } else if (failedBefore !== false) {
                if (failedBefore.reason === `NO_VECTOR_DATA_STORE`) {
                    console.error(`Failed to switch layer while attempting to get the vector data store for ${vectorLayerId} (probably it is not the vector layer)`);
                } else {
                    console.error(`Unknown switch layer failure for ${vectorLayerId}`);
                }

                resolve();
            } else {
                meta.init(gc2Id, true, true).then(layerMeta => {
                    // Trying to recreate the layer tree with updated meta and switch layer again
                    layerTree.create().then(() => {
                        // All layers are guaranteed to exist in meta
                        let currentLayers = layers.getLayers();
                        if (currentLayers && Array.isArray(currentLayers)) {
                            layers.getLayers().split(',').map(layerToActivate => {
                                _self.checkLayerControl(layerToActivate, doNotLegend, setupControls);
                            });
                        }

                        _self.init(vectorLayerId, true, false, false, true, {
                            reason: `NO_VECTOR_DATA_STORE`
                        }).then(() => {
                            resolve();
                        });
                    });
                }).catch(() => {
                    console.error(`Could not add ${gc2Id} vector layer`);
                    layers.decrementCountLoading(vectorLayerId);
                    resolve();
                });
{'fraction_non_alphanumeric': 0.1068134483784588, 'fraction_numerical': 0.004016661707825052, 'mean_word_length': 1.668717745136959, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '495381', 'n_tokens_mistral': 3597, 'n_tokens_neox': 3386, 'n_words': 827}