'use strict';
var turf = require('turf');
var preserveType = require('./value_area');

// Find unclosed ways.
module.exports = function(tileLayers, tile, writeData, done) {
  var layer = tileLayers.osm.osm;
  var bbox = turf.extent(layer);
  var bboxLineString = turf.bboxPolygon(bbox);
  bboxLineString.geometry.type = 'LineString';
  bboxLineString.geometry.coordinates = bboxLineString.geometry.coordinates[0];
  var buffer = turf.buffer(bboxLineString, 0.0005, 'miles').features[0];

  var result = layer.features.filter(function(val) {
    val.properties._osmlint = 'unclosedways';
    var valueType = (
      preserveType.area[val.properties.area] ||
      preserveType.building[val.properties.building] ||
      preserveType.landuse[val.properties.landuse] ||
      preserveType.aeroway[val.properties.aeroway] ||
      preserveType.leisure[val.properties.leisure] ||
      preserveType.natural[val.properties.natural] ||
      preserveType.man_made[val.properties.man_made]
    );

    if (val.geometry.type === 'LineString' && valueType && !(val.properties.source && val.properties.source === 'NHD')) {
      var coordinates = val.geometry.coordinates;
      var firstCoord = coordinates[0];
      var lastCoord = coordinates[coordinates.length - 1];
      if (turf.inside(turf.point(firstCoord), buffer) || turf.inside(turf.point(lastCoord), buffer)) {
        return false;
      }
      return true;
    }
  });

  if (result.length > 0) {
    var fc = turf.featurecollection(result);
    writeData(JSON.stringify(fc) + '\n');
  }

  done(null, null);
};

@@ -280,16 +280,1068 @@
 (bbox);%0A
+  var preventSource = %7B%0A    'NHD': true,%0A    'Kartverket N50': true,%0A    'MetroGIS DataFinder': true,%0A    'CANVEC': true,%0A    'ABS_2006': true,%0A    'Bing:GSI/KIBAN 2005': true,%0A    'BDLL25, EGRN, Instituto Geogr%C3%A1fico Nacional': true,%0A    'Bing;GSI/KIBAN 2500': true,%0A    'CLC2006': true,%0A    'CLC_2006': true,%0A    'CLC_HUN': true,%0A    'CanVec 4.0 - NRCan': true,%0A    'CanVec 6.0 - NRCan': true,%0A    'CanVec 6.0 - NRCan;NRCan-CanVec-7.0': true,%0A    'CanVec_Import_2009': true,%0A    'DCGIS; NPS': true,%0A    'Digital Globe 2011-03-13': true,%0A    'DEP Wetlands (1:12,000) - April 2007 (http://www.mass.gov/mgis/wetdep.htm)': true,%0A    'GSI KIBAN 2500;NARO': true,%0A    'GSI/KIBAN 2500': true,%0A    'GSI/KIBAN 2500, 2008-03-31': true,%0A    'GSI/KIBAN 2500,NARO': true,%0A    'GSI/KIBAN 25000; NARO': true,%0A    'GSI/KIBAN 2500; NARO': true,%0A    'GSI/KIBAN 2500; NARO,Bing-2011-4': true,%0A    'GSI/KIBAN 2500;NARO': true,%0A    'NRCan-CanVec-10.0': true,%0A    'NRCan-CanVec-7.0': true,%0A    'NRCan-CanVec-7.0;CanVec 6.0 - NRCan': true,%0A    'NRCan-CanVec-8.0': true%0A  %7D;%0A
   bboxLi
@@ -1379,16 +1379,16 @@
 tring';%0A
-
   bboxLi
@@ -2121,16 +2121,30 @@
 urce && 
+preventSource%5B
 val.prop
@@ -2160,18 +2160,9 @@
 urce
- === 'NHD'
+%5D
 )) %7B

add preventSource