#!/usr/bin/python
"""
Script to perform bounds checking on a HXL dataset.
David Megginson
November 2014

Check that all #lat_deg and #lon_deg values are contained within the
#GeoJSON featureset provided.

Prerequisites:
- Python Shapely library must be installed: https://pypi.python.org/pypi/Shapely
- libgeos_c must be installed: 

In Ubuntu Linux, the following commands will do the trick:

  sudo apt-get install libgeos-c1
  sudo pip install Shapely

Usage:

  hxlbounds -b BOUNDS.json DATA.csv > report.txt

(Use -h option to get full usage.)

License: Public Domain
Documentation: http://hxlstandard.org
"""

import sys
import argparse
import json
from shapely.geometry import shape
from hxl.filters import parse_tags
from hxl.filters.bounds import hxlbounds

# Command-line arguments
parser = argparse.ArgumentParser(description = 'Perform bounds checking on a HXL dataset.')
parser.add_argument(
    'infile',
    help='HXL file to read (if omitted, use standard input).',
    nargs='?',
    type=argparse.FileType('r'),
    default=sys.stdin
    )
parser.add_argument(
    'outfile',
    help='HXL file to write (if omitted, use standard output).',
    nargs='?',
    type=argparse.FileType('w'),
    default=sys.stdout
    )
parser.add_argument(
    '-b',
    '--bounds',
    help='GeoJSON file containing the boundary information.',
    required=True,
    type=argparse.FileType('r')
    )
parser.add_argument(
    '-c',
    '--tags',
    help='Comma-separated list of column tags to include in error reports',
    metavar='tag,tag...',
    type=parse_tags,
    default='loc,org,sector,adm1,adm2,adm3'
    )
args = parser.parse_args()

data = json.load(args.bounds)
shapes = []
for d in data['features']:
    shapes.append(shape(d['geometry']))

# Call the command function
hxlbounds(args.infile, args.outfile, shapes, tags=args.tags)

# end
