
/**
  The tag mapper is responsible for mapping OSM tag information in to the
  document model, using a variety of different schemas found in /schema/*.
**/

var through = require('through2'),
    trimmer = require('trimmer'),
    merge = require('merge');

var NAME_SCHEMA = require('../schema/name_osm');
var ADDRESS_SCHEMA = merge( true, false,
  require('../schema/address_osm'),
  require('../schema/address_naptan'),
  require('../schema/address_karlsruhe')
);

module.exports = function(){

  var stream = through.obj( function( doc, enc, done ) {

    var tags = doc.getMeta('tags');
    if( tags ){

      // Unfortunately we need to iterate over every tag,
      // so we only do the iteration once to save CPU.
      for( var tag in tags ){

        // Map localized names which begin with 'name:'
        // @ref: http://wiki.openstreetmap.org/wiki/Namespace#Language_code_suffix
        if( tag.match('name:') ){
          var val = trim( tags[tag] );
          if( val ){
            doc.setName( tag.replace('name:',''), val );
          }
        }

        // Map name data from our name mapping schema
        else if( tag in NAME_SCHEMA ){
          var val = trim( tags[tag] );
          if( val ){
            doc.setName( NAME_SCHEMA[tag], val );
          }
        }

        // Map address data from our address mapping schema
        else if( tag in ADDRESS_SCHEMA ){
          var val = trim( tags[tag] );
          if( val ){
            doc.setAddress( ADDRESS_SCHEMA[tag], val );
          }
        }
      }
    }

    this.push( doc );
    done();

  });
  
  // catch stream errors
  stream.on( 'error', console.error.bind( console, __filename ) );

  return stream;
};

// Clean string of leading/trailing junk chars
function trim( str ){
  return trimmer( str, '#$%^*()<>-=_{};:",./?\' ' );
}
@@ -929,32 +929,33 @@
          var val
+1
  = trim( tags%5Bta
@@ -969,32 +969,33 @@
          if( val
+1
  )%7B%0A            
@@ -1031,24 +1031,25 @@
 e:',''), val
+1
  );%0A        
@@ -1165,32 +1165,33 @@
          var val
+2
  = trim( tags%5Bta
@@ -1205,32 +1205,33 @@
          if( val
+2
  )%7B%0A            
@@ -1256,32 +1256,33 @@
 SCHEMA%5Btag%5D, val
+2
  );%0A          %7D%0A
@@ -1411,16 +1411,17 @@
  var val
+3
  = trim(
@@ -1451,16 +1451,17 @@
  if( val
+3
  )%7B%0A    
@@ -1508,16 +1508,17 @@
 ag%5D, val
+3
  );%0A    

fix lint warnings