#!/usr/bin/env python

"""

This script takes a file containing one or more region definitions, that is
pointed to by the -r flag. It then writes each region defition out to it's own
independent file in an autogenerated directory tree.

"""

import sys, os, glob, shutil, numpy
import json
import argparse
from region_utils.region_write_utils import *

parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-r", "--regions_file", dest="regions_file", help="File containing regions to split up", metavar="FILE")

args = parser.parse_args()

if not args.regions_file:
	parser.error('A region file is required.')

if args.regions_file:
	if not os.path.exists(args.regions_file):
		parser.error('The file %s does not exist.'%(args.regions_file))

with open(args.regions_file) as f:
	regions_file = json.load(f)


for feature in regions_file['features']:
	region_name = feature['properties']['name']
	component = feature['properties']['component']
	object_dir = "%s"%(feature['properties']['object'])

	dir_name = region_name.strip().replace(' ','_').strip('\'').strip('.',)

	if not os.path.exists('%s/%s/%s'%(component, object_dir, dir_name)):
		os.makedirs('%s/%s/%s'%(component, object_dir, dir_name))

	out_file = open('%s/%s/%s/region.geojson'%(component, object_dir, dir_name), 'w')

	out_file.write('{"type": "FeatureCollection",\n')
	out_file.write(' "features":\n')
	out_file.write('\t[\n')
	write_single_region(feature, out_file, '\t\t')
	out_file.write('\n')
	out_file.write('\t]\n')
	out_file.write('}\n')
	out_file.close()


