import arcpy
import arcgisscripting
import random
import math
import os
import shutil
newpath = r"C:\\geomask_data\\"
if not os.path.exists(newpath): os.makedirs(newpath)


arcpy.env.overwriteOutput = True

def setupMask():
    OriginalPoint = arcpy.GetParameterAsText(0)
    xcoor = arcpy.GetParameterAsText(1)  # set to field
    ycoor = arcpy.GetParameterAsText(2)  # set to field
    BasePolygon = arcpy.GetParameterAsText(3) # for gp.SelectLayerbyAttribute
    
    den_field = arcpy.GetParameterAsText(4)
    polygon_for_SWM = arcpy.GetParameterAsText(5)
    SWMfield = arcpy.GetParameterAsText(6)

    LakePolygon = arcpy.GetParameterAsText(7)
    output = arcpy.GetParameterAsText(8)
    
    
    
    Mask(OriginalPoint, xcoor,ycoor, BasePolygon,den_field,polygon_for_SWM,SWMfield,LakePolygon, output)

    
def Mask(OriginalPoint, xcoor,ycoor, BasePolygon,den_field,polygon_for_SWM,SWMfield,LakePolygon, output):
    outputname = output
    d_field = den_field
    target_features2 = LakePolygon
    s_field = SWMfield


    target_features = BasePolygon
    Density = []
    sc = arcpy.SearchCursor(target_features)
    row = sc.next()
    while row:
        Density.append(row.getValue(d_field))
        row = sc.next()
    
    InputPoint = OriginalPoint
    sc = arcpy.SearchCursor(InputPoint)
    row = sc.next()
    p_x = []
    p_y = []
    x_field = xcoor
    y_field = ycoor
    while row:
        p_x.append(row.getValue(x_field))
        p_y.append(row.getValue(y_field))
        row = sc.next()

    # store x, y, then we create single point

    i =0
    num = len(p_x)
    TownIndex = []
    
    
    
    while i < num:
        output = r"C:\\geomask_data\\" + 'test' + str(i) + '.shp'
        ptList = [ [ p_x[i], p_y[i] ] ]
        pt = arcpy.Point()
        ptGeoms = []

        pt.X = p_x[i]
        pt.Y = p_y[i]
        ptGeoms.append(arcpy.PointGeometry(pt) )
        arcpy.CopyFeatures_management(ptGeoms, output )
        

        # after create single point, store their town id
        
        arcpy.MakeFeatureLayer_management(output,'outputlyr')
        arcpy.SelectLayerByLocation_management(target_features,"COMPLETELY_CONTAINS",'outputlyr')
        sc = arcpy.SearchCursor(target_features)
        row = sc.next()
        TownIndex.append(row.FID)

        

        i += 1


    
        

    # use TownIndex to search neighbors
    # so we must create spatial contguity weights

    base = polygon_for_SWM
    arcpy.GenerateSpatialWeightsMatrix_stats(base,s_field,r"C:\\geomask_data\\contiguity_weight.swm",
                                             "CONTIGUITY_EDGES_ONLY")
    arcpy.ConvertSpatialWeightsMatrixtoTable_stats(r"C:\\geomask_data\\contiguity_weight.swm",
                                                   r"C:\\geomask_data\\contiguity_weight_table")
    # store neighbor weights
    
    FID = []
    NID = []
    sc = arcpy.SearchCursor(r"C:\\geomask_data\\contiguity_weight_table.dbf")
    row = sc.next()
    while row:
        FID.append(row.ID)
        NID.append(row.NID)
        row = sc.next()
    
    a = 0
    b = 0
    c = []  # array c stores neighbor matrix
    # for example, c[41] = [37,38,40]
    
    Neibor = []
    while b < max(FID)+1:
        a = 0
        Neibor = []
        while a < len(FID):
            if FID[a] == b:
                Neibor.append(NID[a])

            a += 1
        c.append(Neibor)
        b += 1

    # we have neighbor matrix
    # use TownIndex, c, Density to search most likely neighbor

    i1 = 0
    i2 = 0
    i3 = 0
    i4 = []
    i6 = []
    
    
    while i1 < len(TownIndex):   # 第一個點在幾號town, 在TownIndex[i1]
        diff = []
        i2 = 0
        i3 = 0
        while i2 < len(c[TownIndex[i1] ]):  # c[幾號town]的鄰居有多個，每一個拿來和原本的town做密度相減
            d = abs( Density[TownIndex[i1]] - Density[ c[TownIndex[i1]][i2] ] )
            diff.append(d)
            i2 += 1


        i2 = 0
        while i2 < len(c[TownIndex[i1] ]):
            d = abs( Density[TownIndex[i1]] - Density[ c[TownIndex[i1]][i2] ] )
            if d == min(diff):
                i4.append(c[TownIndex[i1]][i2])
            i2 += 1

        number = len(i4)-1
        ran = random.randint(0,number)
        i6.append(i4[ran])
        
        i1 += 1

    i5 = 0
    gp = arcgisscripting.create()

    

    
    i7 = []
    turn = 0
    while i5 < len(i6):
        xxx = i6[i5]
        gp = arcgisscripting.create()
        #arcpy.SelectLayerByAttribute_management( BasePolygon,"NEW_SELECTION",'\"FID\" = %s' % i5 )  # SQL can  use i5
        gp.SelectLayerbyAttribute(target_features,"NEW_SELECTION",'\"FID\" = %s' % xxx)
        newpath = r"C:\\geomask_data\\"
        target_features = BasePolygon
        
        
        arcpy.CreateRandomPoints_management(newpath,  "samplepoints" + str(i5), target_features, "", 1)

        #gp.SelectLayerByAttribute_management(BasePolygon, "CLEAR_SELECTION", "")
        #del gp
                
                


        
        name = "C:\\geomask_data\\samplepoints" + str(i5) + ".shp"
        outputlyr = 'outputlyr' + str(i5)
        #arcpy.MakeFeatureLayer_management(name,'outputlyr'+str(i5))
        
        gp.MakeFeatureLayer(name,outputlyr)
        #arcpy.SelectLayerByLocation_management(outputlyr,"COMPLETELY_WITHIN",target_features2)
        #要看點有沒有落在barrier裡面
        gp.SelectLayerByLocation_management(outputlyr,"WITHIN",target_features2,"","NEW_SELECTION")
        count2 = gp.GetCount_management(outputlyr)
        gp.DeleteFeatures_management(outputlyr)
        turn += 1
        if turn == 15:
            there_is_something_wrong_within_barrier_and_basepolygon
        
        #count2 = int( arcpy.GetCount_management(outputlyr).getOutput(0) )
        #arcpy.Delete_management( outputlyr )
        if count2 == 0:
            turn = 0
            i7.append(name)
            
            
            
        
   #     if count2 == 1:  # random again
    #        newIndex = 0
     #       while newIndex <1:
      #          gp.SelectLayerbyAttribute(target_features,"NEW_SELECTION",'\"FID\" = %s' % xxx)
       #         arcpy.CreateRandomPoints_management(newpath,  "samplepoints" + str(i5), target_features, "", 1)
        #        gp.SelectLayerByAttribute_management(target_features, "CLEAR_SELECTION", "")
         #       name = "C:\\geomask_data\\samplepoints" + str(i5) + ".shp"
          #      outputlyr = 'outputlyr' + str(i5)
           #     arcpy.MakeFeatureLayer_management(name,outputlyr)
            #    arcpy.SelectLayerByLocation_management(outputlyr,"COMPLETELY_WITHIN",target_features2,"","NEW_SELECTION")
             #   count2 = int( arcpy.GetCount_management(outputlyr).getOutput(0) )
              #  arcpy.Delete_management( outputlyr )
               # if count2 == 0:
                #    newIndex += 1
#
 #           i7.append(name)
            
            #arcpy.DeleteFeatures_management( 'outputlyr' )
            
            i5 += 1
        
        
        
    
    #gp.SelectLayerByAttribute_management(BasePolygon, "CLEAR_SELECTION", "")
    

    arcpy.Merge_management(i7,outputname)
    

        

if __name__ == "__main__":
    setupMask()
    print 'Finish' 
        
    

    
            



        
        
            
    

        
        

        
        
        
    
        
        
    
    
    
    
    
