<commit_before>"use strict";

var $ = require('jquery'),
    _ = require('lodash'),
    JSZip = require('jszip'),
    L = require('leaflet'),
    Marionette = require('../../shim/backbone.marionette'),
    turfBboxPolygon = require('turf-bbox-polygon'),
    turfDestination = require('turf-destination'),
    turfIntersect = require('turf-intersect'),
    turfKinks = require('turf-kinks'),
    shapefile = require('shapefile'),
    reproject = require('reproject'),
    router = require('../router').router,
    App = require('../app'),
    utils = require('./utils'),
    models = require('./models'),
    settings = require('../core/settings'),
    coreUtils = require('../core/utils'),
    drawUtils = require('../draw/utils'),
    splashTmpl = require('./templates/splash.html'),
    windowTmpl = require('./templates/window.html'),
    aoiUploadTmpl = require('./templates/aoiUpload.html'),
    drawToolTmpl = require('./templates/drawTool.html'),
    settings = require('../core/settings'),
    modalModels = require('../core/modals/models'),
    modalViews = require('../core/modals/views');

var selectBoundary = 'selectBoundary',
    drawArea = 'drawArea',
    delineateWatershed = 'delineateWatershed',
    aoiUpload = 'aoiUpload',
    freeDraw = 'free-draw',
    squareKm = 'square-km';

var codeToLayer = {}; // code to layer mapping

// The shapefile library relies on a native Promise implementation,
// a polyfill for which is available in the JSZip library
if (!window.Promise) {
    window.Promise = JSZip.external.Promise;
}

function displayAlert(message, alertType) {
    if (message === drawUtils.CANCEL_DRAWING) {
        return;
    }

    var alertView = new modalViews.AlertView({
        model: new modalModels.AlertModel({
            alertMessage: message,
            alertType: alertType
        })
    });

    alertView.render();
}

function actOnUI(datum, bool) {
    var code = datum.code,
        $el = $('#' + code);

    if (bool) {
        $el.prop('disabled', true);
    } else {
        $el.prop('disabled', false);
    }
}

function actOnLayer(datum) {
    $('#boundary-label').hide();
    if (datum.code && codeToLayer[datum.code]) {
        codeToLayer[datum.code]._clearBgBuffer();
    }
}

function validateRwdShape(result) {
    var d = new $.Deferred();
    if (result.watershed) {
        if (result.watershed.features[0].geometry.type === 'MultiPolygon') {
            d.reject('Unfortunately, the watershed generated at this ' +
                     'location is not available for analysis');
        }
        validateShape(result.watershed)
            .done(function() {
                d.resolve(result);
            })
            .fail(d.reject);
    } else {
        var message = 'Unable to delineate watershed at this location';
        d.reject(message);
    }
    return d.promise();
}

function validateShape(polygon) {
    var d = new $.Deferred(),
        selfIntersectingShape = turfKinks(polygon).features.length > 0;

    if (selfIntersectingShape) {
        var errorMsg = 'This watershed shape is invalid because it intersects ' +
                       'itself. Try drawing the shape again without crossing ' +
                       'over its own border.';
        d.reject(errorMsg);
    } else if (!utils.isValidForAnalysis(polygon)) {
        var maxArea = utils.MAX_AREA.toLocaleString(),
            selectedBoundingBoxArea = Math.floor(utils.shapeBoundingBoxArea(polygon)).toLocaleString(),
            message = 'Sorry, the bounding box of the selected area is too large ' +
                      'to analyze or model. ' + selectedBoundingBoxArea + '&nbsp;km² were ' +
                      'selected, but the maximum supported size is ' +
                      'currently ' + maxArea + '&nbsp;km².';
        d.reject(message);
    } else if (!utils.withinConus(polygon)) {
        var conusMessage = 'The area of interest must be within the Continental US.';
        d.reject(conusMessage);
    } else {
        d.resolve(polygon);
    }
    return d.promise();
}

function validatePointWithinDataSourceBounds(latlng, dataSource) {
    var point = L.marker(latlng).toGeoJSON(),
        d = $.Deferred(),
        perimeter = null,
        point_outside_message = null;

    switch (dataSource) {
        case utils.DRB:
            var streamLayers = settings.get('stream_layers');
            perimeter = _.findWhere(streamLayers, {code: 'drb_streams_v2'}).perimeter;
            point_outside_message = 'Selected point is outside the Delaware River Basin';
            break;
        case utils.NHD:
            // Bounds checking disabled until #1656 is complete.
            d.resolve(latlng);
            return d.promise();
        default:
            var message = 'Not a valid data source';
            d.reject(message);
            return d.promise();
    }

    if (turfIntersect(point, perimeter)) {
        d.resolve(latlng);
    } else {
        d.reject(point_outside_message);
    }
    return d.promise();
}

var DrawWindow = Marionette.LayoutView.extend({
    // model: ToolbarModel,

    template: windowTmpl,

    id: 'draw-window',

    regions: {
        selectBoundaryRegion: '#select-boundary-region',
        drawAreaRegion: '#draw-area-region',
        watershedDelineationRegion: '#watershed-delineation-region',
        uploadFileRegion: '#upload-file-region'
    },

    initialize: function() {
        var map = App.getLeafletMap(),
            ofg = L.featureGroup();
        this.model.set('outlineFeatureGroup', ofg);
        map.addLayer(ofg);
        this.rwdTaskModel = new models.RwdTaskModel();
    },

    onShow: function() {
        var self = this,
            resetRwdDrawingState = function() {
                self.resetDrawingState({
                    clearOnFailure: false<commit_msg>Remove RWD point if RWD cancel button is clicked<commit_after>"use strict";

var $ = require('jquery'),
    _ = require('lodash'),
    JSZip = require('jszip'),
    L = require('leaflet'),
    Marionette = require('../../shim/backbone.marionette'),
    turfBboxPolygon = require('turf-bbox-polygon'),
    turfDestination = require('turf-destination'),
    turfIntersect = require('turf-intersect'),
    turfKinks = require('turf-kinks'),
    shapefile = require('shapefile'),
    reproject = require('reproject'),
    router = require('../router').router,
    App = require('../app'),
    utils = require('./utils'),
    models = require('./models'),
    settings = require('../core/settings'),
    coreUtils = require('../core/utils'),
    drawUtils = require('../draw/utils'),
    splashTmpl = require('./templates/splash.html'),
    windowTmpl = require('./templates/window.html'),
    aoiUploadTmpl = require('./templates/aoiUpload.html'),
    drawToolTmpl = require('./templates/drawTool.html'),
    settings = require('../core/settings'),
    modalModels = require('../core/modals/models'),
    modalViews = require('../core/modals/views');

var selectBoundary = 'selectBoundary',
    drawArea = 'drawArea',
    delineateWatershed = 'delineateWatershed',
    aoiUpload = 'aoiUpload',
    freeDraw = 'free-draw',
    squareKm = 'square-km';

var codeToLayer = {}; // code to layer mapping

// The shapefile library relies on a native Promise implementation,
// a polyfill for which is available in the JSZip library
if (!window.Promise) {
    window.Promise = JSZip.external.Promise;
}

function displayAlert(message, alertType) {
    if (message === drawUtils.CANCEL_DRAWING) {
        return;
    }

    var alertView = new modalViews.AlertView({
        model: new modalModels.AlertModel({
            alertMessage: message,
            alertType: alertType
        })
    });

    alertView.render();
}

function actOnUI(datum, bool) {
    var code = datum.code,
        $el = $('#' + code);

    if (bool) {
        $el.prop('disabled', true);
    } else {
        $el.prop('disabled', false);
    }
}

function actOnLayer(datum) {
    $('#boundary-label').hide();
    if (datum.code && codeToLayer[datum.code]) {
        codeToLayer[datum.code]._clearBgBuffer();
    }
}

function validateRwdShape(result) {
    var d = new $.Deferred();
    if (result.watershed) {
        if (result.watershed.features[0].geometry.type === 'MultiPolygon') {
            d.reject('Unfortunately, the watershed generated at this ' +
                     'location is not available for analysis');
        }
        validateShape(result.watershed)
            .done(function() {
                d.resolve(result);
            })
            .fail(d.reject);
    } else {
        var message = 'Unable to delineate watershed at this location';
        d.reject(message);
    }
    return d.promise();
}

function validateShape(polygon) {
    var d = new $.Deferred(),
        selfIntersectingShape = turfKinks(polygon).features.length > 0;

    if (selfIntersectingShape) {
        var errorMsg = 'This watershed shape is invalid because it intersects ' +
                       'itself. Try drawing the shape again without crossing ' +
                       'over its own border.';
        d.reject(errorMsg);
    } else if (!utils.isValidForAnalysis(polygon)) {
        var maxArea = utils.MAX_AREA.toLocaleString(),
            selectedBoundingBoxArea = Math.floor(utils.shapeBoundingBoxArea(polygon)).toLocaleString(),
            message = 'Sorry, the bounding box of the selected area is too large ' +
                      'to analyze or model. ' + selectedBoundingBoxArea + '&nbsp;km² were ' +
                      'selected, but the maximum supported size is ' +
                      'currently ' + maxArea + '&nbsp;km².';
        d.reject(message);
    } else if (!utils.withinConus(polygon)) {
        var conusMessage = 'The area of interest must be within the Continental US.';
        d.reject(conusMessage);
    } else {
        d.resolve(polygon);
    }
    return d.promise();
}

function validatePointWithinDataSourceBounds(latlng, dataSource) {
    var point = L.marker(latlng).toGeoJSON(),
        d = $.Deferred(),
        perimeter = null,
        point_outside_message = null;

    switch (dataSource) {
        case utils.DRB:
            var streamLayers = settings.get('stream_layers');
            perimeter = _.findWhere(streamLayers, {code: 'drb_streams_v2'}).perimeter;
            point_outside_message = 'Selected point is outside the Delaware River Basin';
            break;
        case utils.NHD:
            // Bounds checking disabled until #1656 is complete.
            d.resolve(latlng);
            return d.promise();
        default:
            var message = 'Not a valid data source';
            d.reject(message);
            return d.promise();
    }

    if (turfIntersect(point, perimeter)) {
        d.resolve(latlng);
    } else {
        d.reject(point_outside_message);
    }
    return d.promise();
}

var DrawWindow = Marionette.LayoutView.extend({
    // model: ToolbarModel,

    template: windowTmpl,

    id: 'draw-window',

    regions: {
        selectBoundaryRegion: '#select-boundary-region',
        drawAreaRegion: '#draw-area-region',
        watershedDelineationRegion: '#watershed-delineation-region',
        uploadFileRegion: '#upload-file-region'
    },

    initialize: function() {
        var map = App.getLeafletMap(),
            ofg = L.featureGroup();
        this.model.set('outlineFeatureGroup', ofg);
        map.addLayer(ofg);
        this.rwdTaskModel = new models.RwdTaskModel();
    },

    onShow: function() {
        var self = this,
            resetRwdDrawingState = function(e) {
                // If the cancel button was clicked
                if (e && e.type === 'click') {
                    self.model.clearRwdClickedPoint(App.getLeafletMap());
                }

                self.resetDrawingState({
                    clearOnFailure: false
{'fraction_non_alphanumeric': 0.13141025641025642, 'fraction_numerical': 0.0011808367071524967, 'mean_word_length': 2.395475372279496, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '4865309', 'n_tokens_mistral': 3521, 'n_tokens_neox': 3385, 'n_words': 760}