import arcpy
import os
import shutil
import random



newpath = r"C:\\geomask_data\\"
if not os.path.exists(newpath): os.makedirs(newpath)
arcpy.env.overwriteOutput = True


def setupPixelAgg():
    OriginalPoints =  arcpy.GetParameterAsText(0)
    #xcoor = arcpy.GetParameterAsText(1)
    #ycoor = arcpy.GetParameterAsText(2)
    #PixelSize = arcpy.GetParameter(3)
    NumCell = arcpy.GetParameter(1)
    
    
    
    
    OutputName= arcpy.GetParameterAsText(2)
    PixelAgg(OriginalPoints,NumCell,OutputName)
    

def PixelAgg(OriginalPoints,NumCell,OutputName):
     
    InputPoint =  OriginalPoints
    arcpy.AddXY_management(InputPoint)
   
    numberCellX = NumCell  # x ¶b­n´X®æ
    
    output = OutputName
    
    

    p_x = []
    p_y = []
    sc = arcpy.SearchCursor(InputPoint)
    row = sc.next()
    while row:
        p_x.append(row.POINT_X)
        p_y.append(row.POINT_Y)
        row = sc.next()

    # store x, y,then create fishnet
    width = max(p_x) - min(p_x)
    height = max(p_y) - min(p_y)
    
    CellSize = width / numberCellX
    numberCellY = int(height / CellSize) +3
    
    # fishnet base point
    minXminY = str( min(p_x) ) + " " + str( min(p_y)- CellSize)
    minXmaxY = str( min(p_x) ) + " " + str( max(p_y))

    join_name = "C:\\geomask_data\\fishnet" + str(random.randint(0,99999999999)) + ".shp"
    arcpy.CreateFishnet_management(join_name,minXminY,minXmaxY,CellSize,CellSize,numberCellY,numberCellX,"#","NO_LABELS","#","POLYGON")
    arcpy.SpatialJoin_analysis(join_name,InputPoint,OutputName)
    





if __name__ == "__main__":
    setupPixelAgg()
    #shutil.rmtree(newpath)

#minX = "174363.652930 2491625.826990"
#minXmaxY = "174363.652930 2514574.223734"
#arcpy.CreateFishnet_management("D:\\Data\\fishnet.shp",minX,minXmaxY,200,200,100,100,"#","NO_LABELS","#","POLYGON")
