# Path: farmsList/settings.py
# class ProdConfig(Config):
#     """Production configuration."""
#     ENV = 'prod'
#     DEBUG = False
#     SQLALCHEMY_DATABASE_URI = os_env.get('HEROKU_POSTGRESQL_IVORY_URL')
#     DEBUG_TB_ENABLED = False  # Disable Debug toolbar
#     HTTP_SERVER = "acres.herokuapp.com"
# 
# class DevConfig(Config):
#     """Development configuration."""
#     ENV = 'dev'
#     DEBUG = True
#     MAIL_DEBUG = True
#     DB_NAME = 'dev.db'
#     # Put the db file in project root
#     # DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
#     SQLALCHEMY_DATABASE_URI = 'postgresql://urbanlandlocatoradmin:@localhost/urban_land_locator' #'sqlite:///{0}'.format(DB_PATH)
#     DEBUG_TB_ENABLED = True
#     ASSETS_DEBUG = True  # Don't bundle/minify static assets
#     HTTP_SERVER = "localhost:5001"


import os
import json
import execjs
import urllib2
from sqlalchemy import create_engine
from farmsList.settings import ProdConfig, DevConfig

soilsFile = open("parcels-pristine/yolo-soils.geojson")
yoloSoils = json.loads(soilsFile.read())
soilsArray = yoloSoils['features']

# For now, we pretty much assume that land is correctly soiled on a first come first serve basis in terms of importing new soil data.
# This is based on the nature of frequency with which such data sets are updated.
# Currently, the government is only responsible for collecting this data on an ad hoc basis.
for soilFeature in soilsArray:
	stringVersion = json.dumps(soilFeature['geometry'])
	name = 'soil' + soilFeature['properties']['COMPONENT_']
	result = conn.execute("SELECT * FROM additional_layers WHERE name LIKE 'soil%%' AND ST_Intersects(ST_GeomFromGeoJson('{}'), geom) AND (ST_Area(ST_Intersection(ST_GeomFromGeoJson('{}'), geom))/ST_Area(geom)) > .25".format(stringVersion,stringVersion)).first()
	if result == None:
		conn.execute("INSERT INTO additional_layers (name, geometry, geom) VALUES('{}','{}',ST_GeomFromGeoJson('{}'))".format(name,stringVersion, stringVersion))
	elif debug:
		print '{} intersects by more than 25%% with an existing soil geometry ({})'.format(name, result)

for x in range(0, 17):
	filename = 'parcels{0:02d}.json'.format(x)
	file = open("parcels-pristine/" + filename)
	array = json.loads(file.read())
	for y in range(0, len(array)):
		if 'apn' not in array[y]:
			continue
		if int(array[y]['parcode']) != 1 or int(array[y]['apn']) in compiledAPNs:
			continue
		geojsonString = '{{"type":"MultiPolygon","coordinates":[{}]}}'.format(array[y]['shape']['geometry']['rings'])
		point = [float(array[y]['shape']['longitude']), float(array[y]['shape']['latitude'])]
		centerString = '{{"type":"Point","coordinates":{}}}'.format(point)
		soil = ""

# Path: farmsList/settings.py
# class ProdConfig(Config):
#     """Production configuration."""
#     ENV = 'prod'
#     DEBUG = False
#     SQLALCHEMY_DATABASE_URI = os_env.get('HEROKU_POSTGRESQL_IVORY_URL')
#     DEBUG_TB_ENABLED = False  # Disable Debug toolbar
#     HTTP_SERVER = "acres.herokuapp.com"
# 
# class DevConfig(Config):
#     """Development configuration."""
#     ENV = 'dev'
#     DEBUG = True
#     MAIL_DEBUG = True
#     DB_NAME = 'dev.db'
#     # Put the db file in project root
#     # DB_PATH = os.path.join(Config.PROJECT_ROOT, DB_NAME)
#     SQLALCHEMY_DATABASE_URI = 'postgresql://urbanlandlocatoradmin:@localhost/urban_land_locator' #'sqlite:///{0}'.format(DB_PATH)
#     DEBUG_TB_ENABLED = True
#     ASSETS_DEBUG = True  # Don't bundle/minify static assets
#     HTTP_SERVER = "localhost:5001"


# Path: import-westsac-parcel-geometries.py
import os
import json
import execjs
import urllib2
from sqlalchemy import create_engine
from farmsList.settings import ProdConfig, DevConfig


soilsFile = open("parcels-pristine/yolo-soils.geojson")
yoloSoils = json.loads(soilsFile.read())
soilsArray = yoloSoils['features']

# For now, we pretty much assume that land is correctly soiled on a first come first serve basis in terms of importing new soil data.
# This is based on the nature of frequency with which such data sets are updated.
# Currently, the government is only responsible for collecting this data on an ad hoc basis.
for soilFeature in soilsArray:
	stringVersion = json.dumps(soilFeature['geometry'])
	name = 'soil' + soilFeature['properties']['COMPONENT_']
	result = conn.execute("SELECT * FROM additional_layers WHERE name LIKE 'soil%%' AND ST_Intersects(ST_GeomFromGeoJson('{}'), geom) AND (ST_Area(ST_Intersection(ST_GeomFromGeoJson('{}'), geom))/ST_Area(geom)) > .25".format(stringVersion,stringVersion)).first()
	if result == None:
		conn.execute("INSERT INTO additional_layers (name, geometry, geom) VALUES('{}','{}',ST_GeomFromGeoJson('{}'))".format(name,stringVersion, stringVersion))
	elif debug:
		print '{} intersects by more than 25%% with an existing soil geometry ({})'.format(name, result)

for x in range(0, 17):
	filename = 'parcels{0:02d}.json'.format(x)
	file = open("parcels-pristine/" + filename)
	array = json.loads(file.read())
	for y in range(0, len(array)):
		if 'apn' not in array[y]:
			continue
		if int(array[y]['parcode']) != 1 or int(array[y]['apn']) in compiledAPNs:
			continue
		geojsonString = '{{"type":"MultiPolygon","coordinates":[{}]}}'.format(array[y]['shape']['geometry']['rings'])
		point = [float(array[y]['shape']['longitude']), float(array[y]['shape']['latitude'])]
		centerString = '{{"type":"Point","coordinates":{}}}'.format(point)
		soil = ""

		parcel = {}