#!/usr/bin/env python
###############################################################################
# $Id: tigerpoly.py,v 1.3 2003/07/11 14:52:13 warmerda Exp $
#
# Project:  OGR Python samples
# Purpose:  Assemble TIGER Polygons.
# Author:   Frank Warmerdam, warmerdam@pobox.com
#
###############################################################################
# Copyright (c) 2003, Frank Warmerdam <warmerdam@pobox.com>
# 
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###############################################################################
# 
#  $Log: tigerpoly.py,v $
#  Revision 1.3  2003/07/11 14:52:13  warmerda
#  Added logic to replicate all source polygon fields onto output file.
#
#  Revision 1.2  2003/07/11 14:31:17  warmerda
#  Use provided input filename.
#
#  Revision 1.1  2003/03/03 05:17:06  warmerda
#  New
#
#

import osr
import ogr
import string
import sys

infile = sys.argv[1]

#############################################################################
# Open the datasource to operate on.

ds = ogr.Open( "Polygon.shp", update = 0 )
poly_layer = ds.GetLayerByName( 'Polygon' )

ds2 = ogr.Open( infile, update = 0 )
landmark_layer = ds2.GetLayerByName( 'Landmarks' )

ds3 = ogr.Open( infile, update = 0 )
arealandmark_layer = ds3.GetLayerByName( 'AreaLandmarks' )

#############################################################################
#	Create output file for the composed polygons.

outfile = "AreaLandmarks.shp"
shp_driver = ogr.GetDriverByName( 'ESRI Shapefile' )
shp_driver.DeleteDataSource( outfile )

shp_ds = shp_driver.CreateDataSource( outfile )

shp_layer = shp_ds.CreateLayer( 'out', geom_type = ogr.wkbPolygon )

src_defn = landmark_layer.GetLayerDefn()
poly_field_count = src_defn.GetFieldCount()

for fld_index in range(poly_field_count):
    src_fd = src_defn.GetFieldDefn( fld_index )
    
    fd = ogr.FieldDefn( src_fd.GetName(), src_fd.GetType() )
    fd.SetWidth( src_fd.GetWidth() )
    fd.SetPrecision( src_fd.GetPrecision() )
    shp_layer.CreateField( fd )

#############################################################################
# Read all features in the line layer, holding just the geometry in a hash
# for fast lookup by TLID.

polygon = {}
feat = poly_layer.GetNextFeature()
cenid_field = feat.GetFieldIndex( 'CENID' )
polyid_field = feat.GetFieldIndex( 'POLYID' )
while feat is not None:
    cenid = feat.GetField( cenid_field )
    polyid = feat.GetField( polyid_field )
    polygon[cenid, polyid] = feat.GetGeometryRef().Clone()
    feat.Destroy()
    feat = poly_layer.GetNextFeature()

print 'Got %d polygons.' % (len(polygon))

arealandmark = {}
feat = arealandmark_layer.GetNextFeature()
cenid_field = feat.GetFieldIndex( 'CENID' )
polyid_field = feat.GetFieldIndex( 'POLYID' )
land_field = feat.GetFieldIndex( 'LAND' )
while feat is not None:
    cenid  = feat.GetField( cenid_field )
    polyid = feat.GetField( polyid_field )
    land   = feat.GetField( land_field )
    if not arealandmark.has_key(land):
	arealandmark[land] = []
    arealandmark[land].append((cenid, polyid))
    feat.Destroy()
    feat = arealandmark_layer.GetNextFeature()

print 'Got %d area landmarks.' % (len(arealandmark))

#############################################################################
# Process all polygon features.

feat = landmark_layer.GetNextFeature()
land_field = feat.GetFieldIndex( 'LAND' )
poly_count = 0

while feat is not None:
    land = feat.GetField( land_field )

    if not arealandmark.has_key(land):
	feat.Destroy()
	feat = landmark_layer.GetNextFeature()
	continue
    
    for cenid, polyid in arealandmark[land]:
	feat2 = ogr.Feature(feature_def=shp_layer.GetLayerDefn())

	for fld_index in range(poly_field_count):
	    feat2.SetField( fld_index, feat.GetField( fld_index ) )

	feat2.SetGeometry( polygon[cenid, polyid] )

	shp_layer.CreateFeature( feat2 )
	feat2.Destroy()

    poly_count = poly_count + 1
    feat.Destroy()
    feat = landmark_layer.GetNextFeature()

print 'Built %d area landmarks.' % poly_count

#############################################################################
# Cleanup

shp_ds.Destroy()
ds.Destroy()
