#!/usr/local/bin/python
# =========================================================================================
# Script : PostProcessReversBufferAnalysis.py
# -----------------------------------------------------------------------------------------
# Purpose : This application is the post process to measure the horizontal accuracy of the SFWMD 
#          Regulation Permit applications boundary comparing with County based Cadastre Data.
# -----------------------------------------------------------------------------------------
# Suppliment Info:  In this part of the process application will look for the edit id, application 
#                   number and shape length from a microsoft access based query. The edit id is the
#                   unique numbers recorded at the time of GIS spatial data digitizing and recorded
#                   in an Access database table called GIS-GENP.mdb. The Buffer_final field will be 
#                   updating by edit_id.
# -----------------------------------------------------------------------------------------
# Author : Shakir Ahmed, RPS Division, SFWMD, (561)682-2872
# Supervisor : Juan Tobar, RPS Division SFWMD, (561)682-6687
# Create date: March 20/2009
#------------------------------------------------------------------------------------------

# Import system modules
import sys
import string
import os
import arcgisscripting
import odbc
import time
import shutil


# processing arc object
gp = arcgisscripting.create()

class test:
    
    def __init__(self):
        # ESRI Create the Geoprocessor object
        self.gp = arcgisscripting.create()
        # ESRI Set the necessary product code
        if self.gp.CheckProduct("ArcInfo") == "Available":
         #print "Using ArcINFO license..." 
         self.gp.SetProduct("ArcInfo")
        elif self.gp.CheckProduct("ArcView") == "Available":
         #print "Using ArcView license..."
         self.gp.SetProduct("ArcView")
        # ESRI Load required toolboxes...
        self.gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")     

# declearing variables for time
mytime = time.strftime("%m%d")
mytimeMonth = time.strftime('%m')
mytimeDay = time.strftime('%d')
mytimeYear = time.strftime('%Y')

mytimeYMD = time.strftime('%Y%m%d')
mytimex = time.strftime('%m/%d/%Y')
time_sec = time.strftime('%H:%M:%S')

#loading toolboxes from Local Arc GIS installed folder
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Analysis Tools.tbx")

#Declearing the working directory
#dir1 = "//dataserv/420/4240/gis/applications/dev/py/ReverseBufferOverLay"
#dir1 = "//dataserv/420/4240/gis/applications/prd/py/ReverseBufferOverLay"
dir1 = "c:/py/ReverseBufferOverLay"
try:
    
# Creating a log file to write the different process status 
    f=open('%s/log/PostProcessReverseBufferOverLay%s.txt' %(dir1,mytimeYMD), 'w')
    f.write('Start Date/time : %s\n'%time.ctime(time.time()))


# Declearing local variables for different feature Classes...

    permit_line = "%s/gdb/Features_old.mdb/permit_line"%dir1
    permit_line_Buffer = "%s/gdb/Features_old.mdb/permit_line_Buffer"%dir1
    parcel_line_Clip_Dissolve = "%s/gdb/Features_old.mdb/parcel_line_Dissolve"%dir1
    parcel_line_Clip = "%s/gdb/Features_old.mdb/parcel_line_clip"%dir1
    parcel_line = "%s/gdb/Parcel.gdb/Parcel_Data/wmd_parcel_line"%dir1
    parcel_line_Select = "%s/gdb/Features_old.mdb/parcel_line_Select"%dir1
    my_feature = "%s/gdb/Features_old.mdb/my_apps_old"%dir1
    temp_mdb = "%s/gdb/Features_old.mdb"%dir1

    App_accuracy_View = "App_accuracy_View"
    parcel_line_Clip_Layer = "parcel_line_Clip_Layer"
    parcel_line_Clip_Layer__2_ = "parcel_line_Clip_Layer"
    parcel_line_Clip_Layer__3_ = "parcel_line_Clip_Layer"
    
    conn = odbc.odbc("ReverseBufferOverLayold")
    cursor = conn.cursor()
    conn1 = odbc.odbc("ReverseBufferOverLayold")
    cursor1 = conn.cursor()

# Declearng variables for different buffer ranges
    a = [4]
  

    for x in a:
        print x,
        my_category = x
      
        cursor.execute ("SELECT EDIT_ID, APP_NO, Shape_length FROM qry_gis_genp_old")
        
#selcting coulmns by using cursor from Microsoft Access based query, which is connected through odbc.
        i = 0
        while (1):
            row = cursor.fetchone()
            if row == None:
                break
                    
            i = i + 1
            my_edit_id= row[0]
            my_app_id = row[1]
            my_length_1 = row[2]
            
            # showing result on the screen
            print my_edit_id
            print my_app_id
            print my_length_1
            time_sec = time.strftime('%H:%M:%S')
            cursor1.execute("""UPDATE tbl_local_Process_old SET ProcessStartTime = '%s', ProcessDate = '%s' where EDIT_ID = %s """%(time_sec,mytimex,my_edit_id))
            
    
            if gp.exists(permit_line):
                gp.delete_management(permit_line)
            else:
                print "Permit Line Not present"
            my_feature_layer = "PRSTF_APP_AREA_Layer_%s_%s"%(i,my_category)
            gp.MakeFeatureLayer_management(my_feature, my_feature_layer, "", "", "APP_NO APP_NO VISIBLE;GLOBALID GLOBALID VISIBLE;OLD_AREA OLD_AREA VISIBLE;SHAPE_Length SHAPE_Length VISIBLE;SHAPE_Area SHAPE_Area VISIBLE;Distance Distance VISIBLE;PercentResult PercentResult VISIBLE")
    
# Selecting layer by application number which is my_app_id
            gp.SelectLayerByAttribute_management(my_feature_layer, "NEW_SELECTION", "APP_NO = '%s'"%my_app_id)
    
# Converting selected application polygon feature to line
            gp.FeatureToLine_management(my_feature_layer, permit_line, "", "ATTRIBUTES")
    
# creating buffer of the selected application by the buffer category which is 1-10
            if gp.exists(permit_line_Buffer):
                gp.delete_management(permit_line_Buffer)
                #gp.Buffer_analysis(permit_line, permit_line_Buffer, "%s Feet"%my_category, "FULL", "ROUND", "NONE", "")
                gp.Buffer_analysis(permit_line, permit_line_Buffer, "4 Feet", "FULL", "ROUND", "NONE", "")
            else:
                gp.Buffer_analysis(permit_line, permit_line_Buffer, "4 Feet", "FULL", "ROUND", "NONE", "")
    
# Cliping the parcel lines within the buffer distance of the application boundary
            if gp.exists(parcel_line_Clip):
                gp.delete_management(parcel_line_Clip)
                gp.Clip_analysis(parcel_line, permit_line_Buffer, parcel_line_Clip, "")
            else:       
                gp.Clip_analysis(parcel_line, permit_line_Buffer, parcel_line_Clip, "")
    
            if gp.exists(parcel_line_Select):
                gp.delete_management(parcel_line_Select)
                gp.Select_analysis(parcel_line_Clip, parcel_line_Select, "[Shape_Length] >=%s"%my_category)
            else:
                gp.Select_analysis(parcel_line_Clip, parcel_line_Select, "[Shape_Length] >=%s"%my_category)
            
# Dissolve the multiple parcel lines which clipped out from the buffer area and to make one and get the total length of the lines
            if gp.exists(parcel_line_Clip_Dissolve):
                gp.delete_management(parcel_line_Clip_Dissolve)
                gp.Dissolve_management(parcel_line_Select, parcel_line_Clip_Dissolve, "Dis_fac", "", "MULTI_PART")
            else:
                gp.Dissolve_management(parcel_line_Select, parcel_line_Clip_Dissolve, "Dis_fac", "", "MULTI_PART")
            
            count = gp.GetCount_management(parcel_line_Clip_Dissolve)
            
            if count >= 1:
                rows = gp.SearchCursor(parcel_line_Clip_Dissolve)
                row = rows.next()
                my_length_2 = row.Shape_Length
                print my_length_2
                my_final_length = (my_length_2/my_length_1)
    
                result_ratio =  my_final_length      
    
                if x == 10 and my_final_length <= 0.999:
                    my_final_length = 0
                else:
                    print 'nothing'
                # deleting variables 
    
                time_sec = time.strftime('%H:%M:%S')
                #cursor1.execute("""UPDATE local_cmgenapp1 SET BUFFER = %s where EDIT_ID = %s """%(my_category,my_edit_id))       
                cursor1.execute("""UPDATE tbl_local_Process_old SET BUFFER_FINAL = %s,Probability%s = %s,ProcessEndTime = '%s', QAQC_ACCURACY = %s where EDIT_ID = %s """%(my_category,my_category,result_ratio,time_sec, my_final_length,my_edit_id))
                
            else:
                my_final_length = 0
                result_ratio = my_final_length
                print "Parcel line not present within the buffer range"
                time_sec = time.strftime('%H:%M:%S')
                #cursor1.execute("""UPDATE local_cmgenapp1 SET BUFFER = %s where EDIT_ID = %s """%(my_category,my_edit_id))
                cursor1.execute("""UPDATE tbl_local_Process_old SET BUFFER_FINAL = %s,Probability%s = %s,ProcessEndTime = '%s', QAQC_ACCURACY = %s where EDIT_ID = %s """%(my_category,my_category,result_ratio,time_sec, my_final_length,my_edit_id))
       # deleting varialbes

                
        
#deleting variable of the buffer category to run for the second category

    f.write('End Date/time : %s\n'%time.ctime(time.time()))
    f.write('Final Status Success : %s\n'%time.ctime(time.time()))
    #compacting temp geodatabase to enhance performance to run in the next time
    #gp.compact(temp_mdb)
    #conn.close
    #conn1.close
    
    
    print 'Processed Successfully'
except Exception, ErrDesc:
    f.write('End Date/time : %s\n'%time.ctime(time.time()))
    f.write('Status : Failure')