# Path: merge.py
# def merge(buildingIn, addressIn, mergedOut):
#     addresses = []
# 
#     with collection(addressIn, "r") as input:
#         for address in input:
#             shape = asShape(address['geometry'])
#             shape.original = address
#             addresses.append(shape)
# 
#     # Load and index all buildings.
#     buildings = []
#     buildingShapes = []
#     buildingIdx = index.Index()
#     with collection(buildingIn, "r") as input:
#         for building in input:
#             shape = asShape(building['geometry'])
#             building['properties']['addresses'] = []
#             buildings.append(building)
#             buildingShapes.append(shape)
#             buildingIdx.add(len(buildings) - 1, shape.bounds)
# 
#     # Map addresses to buildings.
#     for address in addresses:
#         for i in buildingIdx.intersection(address.bounds):
#             if buildingShapes[i].contains(address):
#                 buildings[i]['properties']['addresses'].append(
#                     address.original)
# 
#     with open(mergedOut, 'w') as outFile:
# 	    outFile.writelines(json.dumps(buildings, indent=4))
# 	    print 'Exported ' + mergedOut


from sys import argv
from glob import glob
from merge import merge
from pprint import pprint
import re
# Tally range-style addresses on a per address file level.

def findRanges(buildings):
    def isQueens(housenumber):
        return bool(re.search(r'(\w+-\w+)', housenumber))
    onlyRanges = 0 ## Buildings with only range house numbers
    onlyRangesQueens = 0 ## Buildings with only range house numbers that are queens style
    rangesAndOther = 0 ## Buildings with range numbers and other numbers
    for building in buildings['buildings']:
        rangeNum = 0 # House number like "10 - 12"
        queensRangeNum = 0 # House number like "10-12 - 10-15"
        total = len(building['properties']['addresses'])
        for address in building['properties']['addresses']:
            p = address['properties']
            if p[u'HOUSE_NU_2'] is not None:
                rangeNum += 1
                if isQueens(p[u'HOUSE_NUMB']) and isQueens(p[u'HOUSE_NU_2']):
                    queensRangeNum += 1
        if rangeNum != 0 and rangeNum == total:
            onlyRanges += 1
        elif rangeNum != 0:
            rangesAndOther = rangesAndOther + 1
        if queensRangeNum !=0 and queensRangeNum == total:
            onlyRangesQueens += 1
    print "%s,%s,%s,%s" % (onlyRanges, onlyRangesQueens, rangesAndOther, len(buildings['buildings']))

# Run conversions. Expects an chunks/addresses-[district id].shp for each
# chunks/buildings-[district id].shp. Optinally convert only one election district.
print "# of buildings where all addresses are a range,# of buildings where all addresses are a range and each address is queens-style, # of buildings with both range and non-range addresses,# of all buildings"
if (len(argv) == 2):

# Path: merge.py
# def merge(buildingIn, addressIn, mergedOut):
#     addresses = []
# 
#     with collection(addressIn, "r") as input:
#         for address in input:
#             shape = asShape(address['geometry'])
#             shape.original = address
#             addresses.append(shape)
# 
#     # Load and index all buildings.
#     buildings = []
#     buildingShapes = []
#     buildingIdx = index.Index()
#     with collection(buildingIn, "r") as input:
#         for building in input:
#             shape = asShape(building['geometry'])
#             building['properties']['addresses'] = []
#             buildings.append(building)
#             buildingShapes.append(shape)
#             buildingIdx.add(len(buildings) - 1, shape.bounds)
# 
#     # Map addresses to buildings.
#     for address in addresses:
#         for i in buildingIdx.intersection(address.bounds):
#             if buildingShapes[i].contains(address):
#                 buildings[i]['properties']['addresses'].append(
#                     address.original)
# 
#     with open(mergedOut, 'w') as outFile:
# 	    outFile.writelines(json.dumps(buildings, indent=4))
# 	    print 'Exported ' + mergedOut


# Path: validation/findranges.py
from sys import argv
from glob import glob
from merge import merge
from pprint import pprint
import re

# Tally range-style addresses on a per address file level.

def findRanges(buildings):
    def isQueens(housenumber):
        return bool(re.search(r'(\w+-\w+)', housenumber))
    onlyRanges = 0 ## Buildings with only range house numbers
    onlyRangesQueens = 0 ## Buildings with only range house numbers that are queens style
    rangesAndOther = 0 ## Buildings with range numbers and other numbers
    for building in buildings['buildings']:
        rangeNum = 0 # House number like "10 - 12"
        queensRangeNum = 0 # House number like "10-12 - 10-15"
        total = len(building['properties']['addresses'])
        for address in building['properties']['addresses']:
            p = address['properties']
            if p[u'HOUSE_NU_2'] is not None:
                rangeNum += 1
                if isQueens(p[u'HOUSE_NUMB']) and isQueens(p[u'HOUSE_NU_2']):
                    queensRangeNum += 1
        if rangeNum != 0 and rangeNum == total:
            onlyRanges += 1
        elif rangeNum != 0:
            rangesAndOther = rangesAndOther + 1
        if queensRangeNum !=0 and queensRangeNum == total:
            onlyRangesQueens += 1
    print "%s,%s,%s,%s" % (onlyRanges, onlyRangesQueens, rangesAndOther, len(buildings['buildings']))

# Run conversions. Expects an chunks/addresses-[district id].shp for each
# chunks/buildings-[district id].shp. Optinally convert only one election district.
print "# of buildings where all addresses are a range,# of buildings where all addresses are a range and each address is queens-style, # of buildings with both range and non-range addresses,# of all buildings"
if (len(argv) == 2):

    findRanges(merge(