import arcpy, common
from networking import BulkConnectionCreator

PARAM_COUNT = 13

with common.runtool(PARAM_COUNT) as parameters:
  places, placesIDField, network, impedance, cutoff, cutoffFld, numToFind, numToFindFld, searchDist, chosenFields, excludeSelf, location, outputName = parameters
  transferFieldList = common.parseFields(chosenFields)
  conn = BulkConnectionCreator(places, placesIDField, location, 
    excludeSelf=common.toBool(excludeSelf, 'self-connection switch'))
  conn.loadNetwork(network, impedance, cutoff=cutoff, numToFind=numToFind, cutoffFld=cutoffFld, numToFindFld=numToFindFld, searchDist=searchDist)
  conn.addPlaceFields(transferFieldList)
  conn.loadPlaces()
  conn.solve()
  conn.output(outputName, PARAM_COUNT)
  conn.close()
# Settlement areas must not cross zone boundaries!

TMP_ZONE_NEGBUF = "tmp_zonecore"
TMP_SETTL_NEGBUF = "tmp_settlcore"
TMP_ROUTES = "tmp_routes"
TMP_ROUTE_ER = "tmp_rerase"
TMP_ROUTE_SINGLE = "tmp_rsing"
TMP_RSING_LAY = "tmp_rsing_lay"

common.progress("parsing attributes")
zoneAreas, zonePts, zoneIDFld, settlAreas, network, impedance, cutoff, cutoffFld, numToFind, location, outputName = common.parameters(
    11
)
common.progress("initializing route creator")
# create network connections - see comments for create_network_connections
conn = BulkConnectionCreator(zonePts, network, impedance, cutoff, numToFind, location)
common.progress("loading data")
conn.load()
common.progress("solving routes")
conn.solve()
common.progress("joining attributes")
conn.joinFields([zoneIDFld])
common.progress("creating routes")
conn.output(TMP_ROUTES)  # routes between the zone central points
conn.close()
arcpy.env.workspace = location
# prepare the settlement areas - remove all lying close to the border
common.progress("clipping settlement areas")
arcpy.Buffer_analysis(zoneAreas, TMP_ZONE_NEGBUF, "-" + borderDist)
arcpy.Clip_analysis(settlAreas, TMP_ZONE_NEGBUF, TMP_SETTL_NEGBUF)
# cut the routes by settlement areas -> connections between them (most expensive)