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" class Email(SurrogatePK, Model):
    __tablename__ = 'emails'
    sender = Column(db.String(80), nullable=False)
    recipients = Column(db.String(2000), nullable=False)
    body = Column(db.String(6250000), nullable=False)
    time_sent = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)

    def __init__(self, sender, recipients, body, **kwargs):
        db.Model.__init__(self, sender=sender, recipients=recipients, body=body, **kwargs)

    def __repr__(self):
        return '<Email(From:{sender};To:{recipient};Body:{body})>'.format(sender=self.sender, recipient=self.recipient, body=self.body) class Farmland(SurrogatePK, Model):
    __tablename__ = 'farmlands'
    size = Column(db.Numeric(precision=6, scale=2), nullable = False)
    hasWater = Column(db.Boolean(), nullable=False, server_default='False')
    water = Column(db.Numeric(precision=3, scale=0), nullable=True)
    public = Column(db.Boolean(), nullable=False, server_default='False')
    soil = Column(db.String(400), nullable=True)
    zoning = Column(db.String(80), nullable=False)
    geometry = Column(Geometry(geometry_type='MULTIPOLYGON'), nullable=False)
    center = Column(Geometry(geometry_type='POINT'), nullable=False)
    developmentPlan = Column(db.String(400), nullable=True)
    ownerName = Column(db.String(400), nullable=True)
    address = Column(db.String(400), nullable=True)
    email = Column(db.String(80), nullable=True)
    monthlyCost = Column(db.Numeric(precision=7, scale=2), nullable = False)
    priorUses = Column(db.String(10000), nullable=True)

    def __init__(self, **kwargs):
        db.Model.__init__(self, **kwargs)

    def __repr__(self):
        return '<Farmland({id})>'.format(id=self.id) class Parcel(SurrogatePK, Model):
    __tablename__ = 'parcels'
    size = Column(db.Numeric(precision=6, scale=2), nullable = False)
    water = Column(db.Numeric(precision=3, scale=0), nullable=True)
    soil = Column(db.String(400), nullable=True)
    zoning = Column(db.String(80), nullable=False)
    geometry = Column(db.String(6250000), nullable=False)
    center = Column(db.String(2000), nullable=False)
    geom = Column(Geometry(geometry_type='MULTIPOLYGON'))
    cent = Column(Geometry(geometry_type='POINT'))
    developmentPlan = Column(db.String(400), nullable=True)
    restrictions = Column(db.String(400), nullable=True)
    address = Column(db.String(400), nullable=True)
    apn = Column(db.BigInteger(), nullable=False, unique=True)
    jurisdiction = Column(db.String(400))
    landType = Column(db.String(80), nullable=True)
    landUse = Column(db.String(80), nullable=True)

    def __init__(self, **kwargs):
        db.Model.__init__(self, **kwargs)

    def __repr__(self):
        return '<Parcel({id})>'.format(id=self.id) class NewParcel1Form(Form):
    address = TextField('Address', validators=[DataRequired()])
    hasWater = BooleanField('The property has a water meter installed.')
    water = TextField('Water Meter Size')
    size = DecimalField('Size (in acres)', validators=[DataRequired()])
    developmentPlan = TextField('Maximum Lease', validators=[DataRequired()])
    monthlyCost = IntegerField('Monthly Cost to Lease', validators=[DataRequired()])
    ownerName = TextField('Name', validators=[DataRequired()])
    email = TextField('Contact E-mail', validators=[DataRequired()])
    geometry = TextField('Geometry', validators=[DataRequired()])
    center = TextField('Center', validators=[DataRequired()])
    knownPriorUses = TextField('Known Prior Uses')

    def __init__(self, *args, **kwargs):
        super(NewParcel1Form, self).__init__(*args, **kwargs)

    def validate(self):
        initial_validation = super(NewParcel1Form, self).validate()
        if not initial_validation:
            return False
        return True class CRUDMixin(object):
class Model(CRUDMixin, db.Model):
class SurrogatePK(object):
    def create(cls, **kwargs):
    def update(self, commit=True, **kwargs):
    def save(self, commit=True):
    def delete(self, commit=True):
    def get_by_id(cls, id):
def ReferenceCol(tablename, nullable=False, pk_name='id', **kwargs): class jsonImportChecker():
	def validateIdsInternally(self, parcels):
		knownConflicts = []
		checkedParcels = {}
		for parcel in parcels:
			parcelId = parcel['id'] + DELIMETER + parcel['jurisdiction']
			if parcelId in checkedParcels and parcelId not in knownConflicts and checkedParcels[parcelId] != parcel:
				knownConflicts.append(parcelId)
			else:
				checkedParcels[parcelId] = parcel
		return knownConflicts

	def validateImportInternalGeometry(self, parcels):
		timestamp = int(time.time())
		indexedParcels = {}
		for parcel in parcels:
			index = parcel['id'] + DELIMETER + parcel['jurisdiction']
			indexedParcels[index] = parcel
		conn.execute("CREATE TEMPORARY TABLE temp_raw_parcels_{}(id VARCHAR(800), geometry GEOMETRY('MultiPolygon'))".format(timestamp))
		sqlCommandsString = "INSERT INTO temp_raw_parcels_{} (id, geometry) VALUES ".format(timestamp)
		for parcel in parcels:
			if 'geometry' in parcel:
				sqlCommandsString += "('{}', ST_GeomFromGeoJson('{}')), ".format(parcel['id'] + DELIMETER + parcel['jurisdiction'], json.dumps(parcel['geometry']))
		sqlCommandsString = sqlCommandsString[:-2]
		conn.execute(sqlCommandsString)
		conn.execute("CREATE TEMPORARY TABLE temp_parcels_polys_{} AS SELECT (ST_Dump(geometry)).geom AS geom FROM temp_raw_parcels_{}".format(timestamp, timestamp))
		conn.execute("CREATE TEMPORARY TABLE temp_rings_{} AS SELECT ST_ExteriorRing((ST_DumpRings(geom)).geom) AS geom FROM temp_parcels_polys_{}".format(timestamp, timestamp))
		conn.execute("CREATE TEMPORARY TABLE temp_boundaries_{} AS SELECT ST_Union(geom) AS geom FROM temp_rings_{}".format(timestamp, timestamp))
		conn.execute("CREATE TEMPORARY SEQUENCE temp_polyseq_{}".format(timestamp))
		conn.execute("CREATE TEMPORARY TABLE temp_polys_{} AS SELECT nextval('temp_polyseq_{}') AS id, (ST_Dump(ST_Polygonize(geom))).geom AS geom FROM temp_boundaries_{}".format(timestamp, timestamp, timestamp))
		knownConflicts = []
		result = conn.execute("SELECT p.id, o.id FROM temp_polys_{} p JOIN temp_raw_parcels_{} o ON ST_Contains(o.geometry, ST_PointOnSurface(p.geom)) ORDER BY p.id".format(timestamp, timestamp)).fetchall()
		currentPolygonId = ''
		currentParcelIds = []
		for row in result:
			polygonId, parcelId = row
			if polygonId == currentPolygonId:
				for currentParcelId in currentParcelIds:
					conflict = (parcelId, currentParcelId)
					if conflict not in knownConflicts:
						knownConflicts.append(conflict)
			else:
				currentPolygonId = polygonId
				currentParcelIds = []
			currentParcelIds.append(parcelId)
		conn.execute('DROP TABLE temp_raw_parcels_{}'.format(timestamp))
		conn.execute('DROP TABLE temp_rings_{}'.format(timestamp))
		conn.execute('DROP TABLE temp_boundaries_{}'.format(timestamp))
		conn.execute('DROP TABLE temp_parcels_polys_{}'.format(timestamp))
		conn.execute('DROP SEQUENCE temp_polyseq_{}'.format(timestamp))
		conn.execute('DROP TABLE temp_polys_{}'.format(timestamp))
		return knownConflicts

	def validateGeometryAgainstExisting(self, parcels):
		timestamp = int(time.time())
		indexedParcels = {}
		for parcel in parcels:
			index = parcel['id'] + DELIMETER + parcel['jurisdiction']
			indexedParcels[index] = parcel
		conn.execute("CREATE TEMPORARY TABLE temp_raw_parcels_{}(id VARCHAR(800), geometry GEOMETRY('MultiPolygon'), preexisting BOOLEAN DEFAULT TRUE)".format(timestamp))
		conn.execute("INSERT INTO temp_raw_parcels_{} (SELECT apn || '{}' || jurisdiction AS id, geom FROM parcels)".format(timestamp, DELIMETER))
		conn.execute("CREATE TEMPORARY TABLE temp_parcels_polys_{} AS SELECT (ST_Dump(geometry)).geom AS geom FROM temp_raw_parcels_{}".format(timestamp, timestamp))
		conn.execute("CREATE TEMPORARY TABLE temp_rings_{} AS SELECT ST_ExteriorRing((ST_DumpRings(geom)).geom) AS geom FROM temp_parcels_polys_{}".format(timestamp, timestamp))
		conn.execute("CREATE TEMPORARY TABLE temp_boundaries_{} AS SELECT ST_Union(geom) AS geom FROM temp_rings_{}".format(timestamp, timestamp))
		conn.execute("CREATE TEMPORARY SEQUENCE temp_polyseq_{}".format(timestamp))
		conn.execute("CREATE TEMPORARY TABLE temp_polys_{} AS SELECT nextval('temp_polyseq_{}') AS id, (ST_Dump(ST_Polygonize(geom))).geom AS geom FROM temp_boundaries_{}".format(timestamp, timestamp, timestamp))
		knownConflicts = []
		conn.execute("CREATE TEMPORARY TABLE temp_single_poly_{} AS SELECT ST_Union(geom) AS geom FROM temp_polys_{}".format(timestamp, timestamp))
		conn.execute("CREATE TEMPORARY TABLE temp_new_parcels_{}(id VARCHAR(800), geometry GEOMETRY('MultiPolygon'))".format(timestamp))
		sqlCommandsString = "INSERT INTO temp_new_parcels_{} (id, geometry) VALUES ".format(timestamp)
		for parcel in parcels:
			if 'geometry' in parcel:
				sqlCommandsString += "('{}', ST_GeomFromGeoJson('{}')), ".format(parcel['id'] + DELIMETER + parcel['jurisdiction'], json.dumps(parcel['geometry']))
		sqlCommandsString = sqlCommandsString[:-2]
		conn.execute(sqlCommandsString)
		result = conn.execute("SELECT n.id FROM temp_single_poly_{} p JOIN temp_new_parcels_{} n ON ST_Intersects(n.geometry, p.geom)".format(timestamp, timestamp)).fetchall()
		conn.execute('DROP TABLE temp_single_poly_{}'.format(timestamp))
		conn.execute('DROP TABLE temp_new_parcels_{}'.format(timestamp))
		for row in result:
			parcelId = row[0]
			if parcelId not in knownConflicts:
				hasGeom = 'geometry' in indexedParcels[index]
				if hasGeom:
					result = conn.execute("SELECT count(*) FROM parcels WHERE geometry = {}".format(indexedParcels[index]['geometry'])).fetchone()
					isNewParcel = result[0] == 0
				if hasGeom and isNewParcel:
					knownConflicts.append(parcelId)
		conn.execute('DROP TABLE temp_raw_parcels_{}'.format(timestamp))
		conn.execute('DROP TABLE temp_rings_{}'.format(timestamp))
		conn.execute('DROP TABLE temp_boundaries_{}'.format(timestamp))
		conn.execute('DROP TABLE temp_parcels_polys_{}'.format(timestamp))
		conn.execute('DROP SEQUENCE temp_polyseq_{}'.format(timestamp))
		conn.execute('DROP TABLE temp_polys_{}'.format(timestamp))
		return knownConflicts

	# This is formatting stuff right now. Ideally, this data would be formatted client side and be made more useful.
	def validateParcels(self, parcels):
		for parcel in parcels:
			if 'id' not in parcel or 'jurisdiction' not in parcel:
				raise IndexError('all parcels must have both an id and a jurisdiction')
			if DELIMETER in parcel['id'] + parcel['jurisdiction']:
				raise ValueError('parcel id or jurisdiction contains delimeter *|*: {} {}'.format(parcel['id'], parcel['jurisdiction']))
		issues = ''

		internalDuplicationErrors = self.validateIdsInternally(parcels)
		if len(internalDuplicationErrors) > 0:
			issues += '\n\r\n\rThese parcels are listed multiple times in your input:\n'
		for duplicate in internalDuplicationErrors:
			parts = duplicate.split(DELIMETER)
			parcelId = parts[0]
			jurisdiction = parts[1]
			issues += '\nID: {}  Jurisdiction: {}'.format(parcelId, jurisdiction)

		internalGeometryErrors = self.validateImportInternalGeometry(parcels)
		if len(internalGeometryErrors) > 0:
			issues += '\n\r\n\rThese parcels within your input overlap:\n'
		for overlap in internalGeometryErrors:
			parcel1, parcel2 = overlap
			parts1 = parcel1.split(DELIMETER)
			parts2 = parcel2.split(DELIMETER)
			parcelId1 = parts1[0]
			jurisdiction1 = parts1[1]
			parcelId2 = parts2[0]
			jurisdiction2 = parts2[1]
			issues += '\nID: {} Jurisdiction: {} overlaps with ID: {} Jurisdiction: {}'.format(parcelId1, jurisdiction1, parcelId2, jurisdiction2)

		existingGeometryConflicts = self.validateGeometryAgainstExisting(parcels)
		if len(existingGeometryConflicts) > 0:
			issues += '\n\r\n\rThese parcels overlap with existing data:\n'
		for overlap in existingGeometryConflicts:
			parts = overlap.split(DELIMETER)
			parcelId = parts[0]
			jurisdiction = parts[1]
			issues += '\nID: {}  Jurisdiction: {}'.format(parcelId, jurisdiction)

		if len(issues) < 1:
			issues = 'No issues!'
		else:
			issues += '\n\r\n\rPlease address this issues and run the import again.\nFor additional help, contact robertm@cityofwestsacramento.org or grantrobertsmith@gmail.com.'
		return issues

	def findUpdates(self, parcels):
		indexedParcels = {}
		for parcel in parcels:
			index = parcel['id'] + DELIMETER + parcel['jurisdiction']
			indexedParcels[index] = parcel
		updatedParcels = {}
		matchingParcels = findExistingMatchingParcels(parcels)
		for row in matchingParcels:
			apn, jurisdiction, geometry, water, zoning, soil, address = row
			index = str(apn) + DELIMETER + jurisdiction
			parcel = indexedParcels[index]
			updatedParcels[index] = []
			if 'geometry' in parcel and geometry != json.dumps(parcel['geometry']):
				tupleEntry = ('geometry', geometry, parcel['geometry'])
				updatedParcels[index].append(tupleEntry)
			if 'water' in parcel and water is not None and water != parcel['water']:
				tupleEntry = ('water', water, parcel['water'])
				updatedParcels[index].append(tupleEntry)
			if 'zoning' in parcel and zoning is not None and zoning.strip() != '' and zoning != parcel['zoning']:
				tupleEntry = ('zoning', zoning, parcel['zoning'])
				updatedParcels[index].append(tupleEntry)
			if 'soil' in parcel and soil is not None and soil.strip() != '' and soil != parcel['soil']:
				tupleEntry = ('soil', soil, parcel['soil'])
				updatedParcels[index].append(tupleEntry)
			if 'address' in parcel and address is not None and address.strip() != '' and address != parcel['address']:
				tupleEntry = ('address', address, parcel['address'])
				updatedParcels[index].append(tupleEntry)
			if updatedParcels[index] == []:
				del updatedParcels[index]
		issues = ''
		for index, parcelUpdates in updatedParcels.iteritems():
			parts = index.split(DELIMETER)
			issues += '\n\r\n\rParcel ID {} and Jurisdiction {} will be updated:\n'.format(parts[0], parts[1])
			for update in parcelUpdates:
				title, oldValue, newValue = update
				issues += '\nThe {} was {} and will be changed to {}.'.format(title, oldValue, newValue)
		if len(issues) < 1:
			issues = 'No issues!'
		else:
			issues += '\n\rTo CONTINUE with the import and ACCEPT THESE CHANGES, click below.'
		return issues class importer():
	def importParcels(self, parcels):
		matchingParcelsRaw = findExistingMatchingParcels(parcels)
		# get the data for the existing parcels and build it out, so updates don't overwrite existing data
		# then in the following loop, we will use it (or defaults) to preset the data[]
		indexedMatchingParcels = {}
		for rawMatchedParcel in matchingParcelsRaw:
			apn, jurisdiction, geometry, water, zoning, soil, address = rawMatchedParcel
			index = str(apn) + "*|*" + jurisdiction
			indexedMatchingParcels[index] = {'geometry': geometry, 'water': water, 'zoning': zoning, 'soil': soil, 'address': address}
		sqlInsertStatement = "INSERT INTO parcels (apn, jurisdiction, geometry, water, zoning, soil, address, center, geom) VALUES "
		sqlUpdateStatementInner = ""
		insertNeeded = False
		updateNeeded = False
		fillData = {'geometry': "", 'water': 0, 'zoning': "Unknown", 'soil': "NULL", 'address': "NULL", 'geom': "NULL"}
		for parcel in parcels:
			#preset the data for updates
			data = {}
			index = parcel['id'] + "*|*" + parcel['jurisdiction']
			isUpdate = index in indexedMatchingParcels
			if isUpdate:
				for dataType, dataValue in indexedMatchingParcels[index].iteritems():
					if dataType == 'geometry':
						data['geom'] = "ST_GeomFromGeoJSON('{}')".format(geometry)
					data[dataType] = dataValue
			# set imported values for either inserts or updates
			neededFillData = deepcopy(fillData)  # track which data isn't being inserted via update
			for dataType in fillData:
				if dataType in parcel:
					if dataType == 'geometry':
						del neededFillData['geom']
						data['geometry'] = json.dumps(parcel['geometry'])
						data['geom'] = "ST_GeomFromGeoJSON('{}')".format(json.dumps(parcel['geometry']))
					else:
						data[dataType] = parcel[dataType]
					del neededFillData[dataType]
			# use defaults for inserts where data not explicitly added
			if not isUpdate:
				for dataType, dataValue in neededFillData.iteritems():
					data[dataType] = dataValue
			sqlStatementInner = "({}, '{}', '{}', {}, '{}', '{}', '{}', '{}', {}), ".format(
				int(parcel['id']), 
				parcel['jurisdiction'], 
				data['geometry'], 
				data['water'], 
				data['zoning'], 
				data['soil'], 
				data['address'], 
				"",
				data['geom']
			)
			if isUpdate:
				updateNeeded = True
				sqlUpdateStatementInner += sqlStatementInner
			else:
				insertNeeded = True
				sqlInsertStatement += sqlStatementInner
		sqlInsertStatement = sqlInsertStatement[:-2]
		sqlUpdateStatementInner = sqlUpdateStatementInner[:-2]
		sqlUpdateStatement = (
			"UPDATE parcels AS p SET "
				"geometry = v.geometry, "
				"water = v.water, "
				"zoning = v.zoning, "
				"soil = v.soil, "
				"address = v.address, "
				"center = v.center, "
				"geom = v.geom "
			"FROM (VALUES "
				"{}"
			") AS v(id, jurisdiction, geometry, water, zoning, soil, address, center, geom) "
			"WHERE p.apn = v.id AND p.jurisdiction = v.jurisdiction"
		).format(sqlUpdateStatementInner)
		if insertNeeded:
			conn.execute(sqlInsertStatement)
		if updateNeeded:
			conn.execute(sqlUpdateStatement)
		conn.execute("UPDATE parcels SET cent = ST_Centroid(geom) WHERE geom IS NOT NULL")
		conn.execute("UPDATE parcels SET center = ST_AsGeoJSON(cent) WHERE geom IS NOT NULL")
		return None
import os
import json
from sqlalchemy import func
from farmsList.settings import ProdConfig, DevConfig
from flask import Blueprint, render_template, session, request, redirect, url_for, flash
from flask.ext.login import login_required
from farmsList.extensions import mail
from flask_mail import Message
from farmsList.user.models import Email
from farmsList.public.models import Farmland,Parcel
from farmsList.public.forms import NewParcel1Form
from farmsList.utils import flash_errors
from farmsList.database import db
from farmsList.modules.importCheckers import jsonImportChecker
from farmsList.modules.importers import importer
# -*- coding: utf-8 -*-




if os.environ.get("FARMSLIST_ENV") == 'prod':
    server = ProdConfig().HTTP_SERVER
else:
    server = DevConfig().HTTP_SERVER

blueprint = Blueprint("user", __name__, url_prefix='/users',
                        static_folder="../static")

@blueprint.route("/approve/<int:farmlandId>")
def approve(farmlandId):
    farmland = Farmland.query.filter(Farmland.id == farmlandId).all()[0]
    db.session.query(Farmland).filter(Farmland.id == farmlandId).update({"public": True})
    db.session.commit()
    msg = Message("Your property is now published on Acres!", recipients=[farmland.email])
    anchorTagHtml = "<a href=\"http://" + server + "/farmland-details/" + str(farmlandId) + "\">the property listing</a>"
    msg.html = ("<html>"
                    "<body>"
                        "<p>Please, visit " + anchorTagHtml + " on Acres to see how it looks.</p>"
                        "<p>Thanks,<br>"
                            "Acres"
                        "</p>"
                    "</body>"
                "</html>")
    mail.send(msg)
    Email.create(sender=msg.sender,
                recipients=",".join(msg.recipients),
                body=msg.html)
    return redirect(url_for('public.home'))

@blueprint.route("/request-changes/<int:farmlandId>")
def reject(farmlandId):
    farmland = Farmland.query.filter(Farmland.id == farmlandId).all()[0]
    msg = Message("Your property cannot be published on Acres", recipients=[farmland.email])
    msg.html = ("<html>"
                    "<body>"
                        "<p>"
                            "We're sorry, but your property cannot be published on Acres at this time. "
                            "Someone will be reaching out to your with more information."
                        "</p>"
                        "<p>Thanks,<br>"
                            "Acres"
                        "</p>"
                    "</body>"
                "</html>")
    mail.send(msg)
    Email.create(sender=msg.sender,
                    recipients=",".join(msg.recipients),
                    body=msg.html)
    return redirect(url_for('public.home'))

@blueprint.route("/list-farmland", methods=['GET', 'POST'])
def list_farmland():
    form = NewParcel1Form(request.form)
    if form.validate_on_submit():
        address = form.address.data
        water = 0 if form.water.data == '' else form.water.data
        zoning = 'Unknown'
        soil = 'Made land'
        geometry = db.session.query(func.ST_GeomFromGeoJSON(form.geometry.data)).all()[0]
        center = db.session.query(func.ST_GeomFromGeoJSON(form.center.data)).all()[0]
        knownParcel = None
        queryResult = db.session.query(Parcel).filter(func.ST_Contains(Parcel.geom, center)).all()
        if len(queryResult) > 0:
            knownParcel = queryResult[0]
            soil = knownParcel.soil
            zoning = knownParcel.zoning
            if water == 0 and knownParcel.water > 0:
                water = knownParcel.water
        new_parcel = Farmland.create(email=form.email.data,
                        ownerName = form.ownerName.data,
                        address=address,
                        size=form.size.data,
                        hasWater = form.hasWater.data,
                        water=water,
                        developmentPlan=form.developmentPlan.data,
                        monthlyCost=form.monthlyCost.data,
                        geometry=geometry,
                        center=center,
                        zoning=zoning,
                        soil=soil,
                        priorUses=form.knownPriorUses.data,
                        public=True)
        return redirect(url_for('public.home'))
    return render_template("users/list-farmland.html", form=form)

@blueprint.route("/import-parcels", methods=['GET', 'POST'])
def import_parcels():
    if request.method == 'POST':
        userVerified = False
        if 'verified' in request.args:
            userVerified = request.args['verified']
            parcels = session['import-data']
        else:
            parcels = json.loads(request.files['importFile'].read())
        if not userVerified:
            session['import-data'] = parcels
            session.modified = True
        review = False
        if userVerified:
            importer().importParcels(parcels)
            issues = 'No issues! Content imported successfully!'
            session.pop('import-data', None)
        else:
            importChecker = jsonImportChecker()
            issues = importChecker.validateParcels(parcels)
            if issues == 'No issues!':
                issues = importChecker.findUpdates(parcels)
            if issues == 'No issues!':

                importer().importParcels(parcels)