# ---------------------------------------------------------------------------
# extract_basin_nlcd_grid_count.py
# Created on: 2014-07-22 18:31:19.00000 (generated by ArcGIS/ModelBuilder)
# Description: extract NLCD gridded data using basin shapefiles and write
# a land cover count summary to csv file
# ---------------------------------------------------------------------------
print 'Importing modules...'
# Import arcpy module
import arcpy
import os
import csv
arcpy.env.overwriteOutput = True
os.chdir("../..")
maindir = os.getcwd()

################### User Input #####################
RFC = 'MBRFC_FY2015'
basins_folder = maindir + '\\' + RFC + '\\Shapefiles\\calb_basins\\'
# if you only want to run specific basins -> list them below
# otherwise set it equal to empty list (basins_overwrite = [])
basins_overwrite = [] 

output_dir = maindir + '\\' + RFC + '\\NLCD\\data_files\\'  # this must contain a folder for each basin (eg. FONN7)

# location of NLCD Raster (CONUS)
if RFC == 'APRFC': # different file for Alaska
    NLCD_Dataset = r'C:\NWS\AK_NLCD_2001\ak_nlcd_2001_land_cover_3-13-08_se5.img'
    #NLCD_Dataset = r'Q:\\GISLibrary\\NLCD\\AK_NLCD_2001\\ak_nlcd_2001_land_cover_3-13-08_se5.img'
else:
    NLCD_Dataset = r'D:\\GIS Library\\NLCD\\nlcd_2011_landcover_2011_edition_2014_03_31.img'
################# End User Input ######################
if not os.path.exists('C:\\NWS\\python\\temp_output\\'):
    print "Missing directory: 'C:\\NWS\\python\\temp_output\\' -> please create"
    raw_input("Press enter to continue processing...")
if not os.path.exists(output_dir):
    print "Missing directory: " + output_dir + " -> please create"
    raw_input("Press enter to continue processing...")

# Check out any necessary licenses
arcpy.CheckOutExtension("spatial")

# Set Geoprocessing environments
#arcpy.env.scratchWorkspace = "D:\\NWS\\GIS\\Models\\10_0_tools\\Model_Output.gdb" # temporary file storage directory
#arcpy.env.parallelProcessingFactor = "50"
print 'ok so far...'

#################################################################################
# find all basins in RFC or only run the specified basin list
basin_files = os.listdir(basins_folder) # list all basin shapefiles in the above specified directory
if len(basins_overwrite) != 0:
    basin_files = basins_overwrite      # use the basins_overright variable to run only specified basins instead of all RFC basins
basins = []
check_dir = os.listdir(output_dir)      # list all folders in output_dir
for each in basin_files:
    if each.split('.')[0] not in basins:
        basins.append(each.split('.')[0])

print 'Identified ' + str(len(basins)) + ' basins in ' + RFC + ' input directory...'        

# loop through basins
for basin in basins:
    ## Script arguments
    Basin_Boundary = basins_folder + '\\' + basin + '.shp'
    basin = 'XX_' + basin # solves issue with basin names containing only numbers (e.g. '2804') 
    print basin 
    
    ## Local variables:
    Basin_Raster = 'C:\\NWS\\python\\temp_output\\' + basin
    Basin_Points = 'C:\\NWS\\python\\temp_output\\' + basin + '_points'
    NLCD = 'C:\\NWS\\python\\temp_output\\' 

    # Process: Extract by Mask
    print 'Clipping raster with basin polygon...'
    #arcpy.gp.ExtractByMask_sa(NLCD_Dataset, Basin_Boundary, Basin_Raster)
    arcpy.Clip_management(NLCD_Dataset, "#", Basin_Raster, Basin_Boundary, "0", "ClippingGeometry")
    
    # Process: Build Raster Attribute Table
    print 'Building basin raster nlcd attribute table...'
    arcpy.BuildRasterAttributeTable_management(Basin_Raster, "Overwrite")
    arcpy.TableToTable_conversion(NLCD_Dataset, NLCD, 'nlcd_table.dbf')

    # Process: Join Field
    print 'Joining field with land cover name...'
    arcpy.JoinField_management(Basin_Raster, "Value", NLCD + 'nlcd_table.dbf', "VALUE", "Land_Cover")
    
    # Process: Table to Table
    print 'Converting to .dbf table...'
    arcpy.TableToTable_conversion(Basin_Raster, NLCD, basin + '_NLCD.dbf')#, "", "Value \"Value\" false false false 4 Long 0 0 ,First,#,P:\\NWS\\GIS\\Models\\Model_Output.gdb\\Extract_img1\\Band_1,Value,-1,-1;Count \"Count\" false false false 8 Double 0 0 ,First,#,P:\\NWS\\GIS\\Models\\Model_Output.gdb\\Extract_img1\\Band_1,Count,-1,-1;Land_Cover \"Land_Cover\" true false false 254 Text 0 0 ,First,#,P:\\NWS\\GIS\\Models\\Model_Output.gdb\\Extract_img1\\Band_1,Land_Cover,-1,-1", "")
    
    # Process: output csv file
    print 'Creating '+ basin.strip('XX_') + '_NLCD.csv file...'
    rows = arcpy.SearchCursor(NLCD + basin + '_NLCD.dbf')
    nlcd_csv = open(output_dir + basin.strip('XX_') + '_NLCD.csv', 'wb')
    csvFile = csv.writer(nlcd_csv) #output csv
    fieldnames = [f.name for f in arcpy.ListFields(NLCD + basin + '_NLCD.dbf')]

    allRows = []
    for row in rows:
        rowlist = []
        for field in fieldnames:
            rowlist.append(row.getValue(field))
        allRows.append(rowlist)
        
    csvFile.writerow(fieldnames)
    for row in allRows:
        csvFile.writerow(row)
    row = None
    rows = None
    nlcd_csv.close()
    
print 'Script completed!!'
