import common, loaders# , regionalization

# OUT_MEASURES = {'TOT_IN_CORE' : 'IN', 'TOT_OUT_CORE' : 'OUT'}
ZONE_MASS_TYPE = {'JOBS' : False, 'EA' : True}

with common.runtool(8) as parameters:
  zoneLayer, zoneIDFld, zoneMassFld, massType, interLayer, interFromIDFld, interToIDFld, interStrengthFld = parameters
  try:
    subtractOutflows = ZONE_MASS_TYPE[massType]
  except KeyError:
    raise ValueError, 'invalid mass type: {}, JOBS or EA allowed'.format(massType)
  zoneSlots = {'id' : zoneIDFld, 'mass' : zoneMassFld}
  interSlots = {'from' : interFromIDFld, 'to' : interToIDFld, 'value' : interStrengthFld}
  # measuresToSlots = {}
  # outSlots = {}
  # for measure in OUT_MEASURES:
    # measuresToSlots[measure] = []
    # for fld in interFlds:
      # slotName = fld + '_' + OUT_MEASURES[measure]
      # measuresToSlots[measure].append(slotName)
      # outSlots[slotName] = slotName
  regload = loaders.RegionalLoader()
  # regionalization.Regionalizer(objects.FunctionalRegion))
  regload.sourceOfZones(zoneLayer, zoneSlots)
  regload.sourceOfInteractions(interLayer, interSlots)
  regload.load()
  zonelist = regload.getZoneList()
  prog = common.progressor('calculating intraflows', len(zonelist))
  intraDict = {}
  for zone in zonelist:
    intraflow = zone.getMass() - zone.sumFlows(out=subtractOutflows)
import arcpy, common
from networking import BulkInteractionCreator

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 = BulkInteractionCreator(places, placesIDField, location,
    excludeSelf=common.toBool(excludeSelf, 'self-interaction 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()
        common.progress('converting to neighbour table')
        tmpTable = pathman.tmpTable()
        arcpy.ConvertSpatialWeightsMatrixtoTable_stats(swm, tmpTable)
        fromFld, toFld = idKeeper.transform(tmpTable, [intIDFld, 'NID'])
        fm = arcpy.FieldMappings()
        fm.addFieldMap(
            common.fieldMap(tmpTable, fromFld, common.NEIGH_FROM_FLD, 'FIRST'))
        fm.addFieldMap(
            common.fieldMap(tmpTable, toFld, common.NEIGH_TO_FLD, 'FIRST'))
        if selfrel:
            query = common.safeQuery(
                "[{}] <> '{}'".format(fromFld, EXTERIOR_ID), tmpTable)
        else:
            query = common.safeQuery(
                "[{0}] <> [{1}] AND [{0}] <> '{2}'".format(
                    fromFld, toFld, EXTERIOR_ID), tmpTable)
        arcpy.TableToTable_conversion(tmpTable, pathman.getLocation(),
                                      pathman.getOutputName(), query, fm)
        common.clearFields(output,
                           [common.NEIGH_FROM_FLD, common.NEIGH_TO_FLD])
    return output


if __name__ == '__main__':
    with common.runtool(5) as parameters:
        zones, idFld, output, exteriorStr, selfrelStr = parameters
        exterior = common.toBool(exteriorStr,
                                 'exterior relationship record switch')
        selfrel = common.toBool(selfrelStr, 'self-neighbourhood record switch')
        table(zones, idFld, output, exterior, selfrel)
import common, regionalization

with common.runtool(regionalization.getMainParamCount()) as parameters:
  regionalization.runByParams(*parameters, delimit=False)
  
  # zoneLayer, zoneIDFld, zoneMassFld, zoneCoopFld, zoneColFld, \
    # interLayer, interStrengthFld, interFromIDFld, interToIDFld, \
    # regionFld, exclavePenal, neighTable, colorFld, measureFlds = common.parameters(14)
  # exclavePenal = common.toFloat(exclavePenal, 'exclave penalization percentage') if exclavePenal else None
  # measureFldList = common.parseFields(measureFlds)
  # regload = loaders.RegionalLoader()
  # regload.requireZones(zoneLayer, zoneIDFld, zoneMassFld, zoneColFld)
  # if regionFld:
    # regload.requirePresets(regionFld, zoneCoopFld, regionalization.Regionalizer(objects.FunctionalRegion))
  # regload.requireInteractions(interLayer, interFromIDFld, interToIDFld, interStrengthFld)
  # regload.requireNeighbourhood(neighTable)
  # regload.load()
  
  # TODO
  # if zoneColFld and colorFld:
    # common.progress('calculating assignment colors')
    # for zone in reg.getZones(): zone.calcFuzzyColor('hamplMembership')
  # common.progress('writing output')
  # zoneLoader.output(zones, None, colorFld=colorFld, measures=measureFldList)