#-------------------------------------------------------------------------------
# Name:			Sediment Wedge Model Generator Aug 2013 Part IV.py
# Purpose:
#
#
# Author:		Dr. Arghya Goswami
# Contact:		arghya.goswami@gmail.com
#
# Created:		06/08/2013
#
# Copyright:	(c) Dr. Arghya Goswami 2013
#
# Licence:		This program is free software; you can redistribute it and/or
#				modify it under the terms of the GNU General Public License,
#				version 2, as published by the Free Software Foundation.
#
#				This program is distributed in the hope that it will be useful,
#				but WITHOUT ANY WARRANTY; without even the implied warranty of
#				MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#				GNU General Public License for more details.
#
#				You should have received a copy of the GNU General Public License
#				along with this program; if not, write to:
#
#				Free Software Foundation, Inc.,
#				51 Franklin St, Fifth Floor,
#				Boston, MA, 02110-1301  USA
#-------------------------------------------------------------------------------
#!/usr/bin/env python
#
#-------------------------------------------------------------------------------
import arcpy, sets, numpy, sys, os, shutil, glob, time, fileinput, string, Tkinter, tkFileDialog
from operator import itemgetter
from Tkinter import *
from arcpy.sa import *
"""-----------------------------------------------------------------------------
# Start Time
-----------------------------------------------------------------------------"""
StartTime = time.asctime(time.localtime(time.time()))
print "Start Time: ", StartTime,"\n"
"""-----------------------------------------------------------------------------
# Check Script name
-----------------------------------------------------------------------------"""
#scriptname = os.path.basename(__file__)
#if "module" in scriptname:
#	print "Please SAVE the script with a Meaningful NAME and RE-RUN!\n"
"""-----------------------------------------------------------------------------
# Definitions used in this Script
-----------------------------------------------------------------------------"""
""" Browse a file function """
def BrowseFile(msg1,indir,ext):
	#Creating Main Window
	root = Tk()
	if ext == "csv":
		desc1 = "Comma Seperated Value Files"
		desc2 = "*." + ext
	elif ext == "txt":
		desc1 = "Text Files"
		desc2 = "*." + ext
	elif ext == "shp":
		desc1 = "Shape Files"
		desc2 = "*." + ext
    # Creating Secondary Window for File Browsing
	filename = tkFileDialog.askopenfilename(filetypes = [(desc1,desc2),('All files','*')], title = msg1, initialdir = indir)
    # Close the Main Window
	root.withdraw()
    # Return Filename
	return filename

""" Browse a directory function """
def BrowseDir(msg2,indir):
    #Creating Main Window
	root = Tk()
    # Creating Secondary Window for Folder Browsing
	dirname = tkFileDialog.askdirectory(title = msg2, initialdir=indir)
    # Close the Main Window
	root.withdraw()
    # Return Dirname
	return dirname

""" Check the existance of a directory function """
def DirCheck(filename):
	# Check if the string is a file name or directory name
	if filename[len(filename)-4] == ".":
		dname = os.path.dirname(filename)
	else:
		dname = filename
	# Check if Dir exists, else create
	if os.path.exists(dname):
	    pass
	else:
	    os.mkdir(dname)
	# Check if the path name if Dir ends with a '/' else add it
	if dname[(len(dname)-1):]=="\\" or dname[(len(dname)-1):] == "/":
		dpath = dname
	else:
		dpath = dname + "/"
	return dpath

""" Returns field names in a shapefile """
def AllFields(infile):
	FieldNnames = []
	fields = arcpy.ListFields(infile)
	FieldNnames = []
	for field in fields:
		FieldNnames.append(field.name)
	return FieldNnames

""" Create the list of files in a folder """
def getFileList(root,ext):
	# for folder path either use "Browse"/"browse" or provide the path to a folder
	# for all filetypes send extention as an empty string (""), else use like ".csv"
	filelist = []
	if root == "Browse" or root == "browse":
		root = BrowseDir("Please select the Directory", "C:/")
	# select the type of file, for instance *.jpg or all files *.*
	for folder in glob.glob(root):
		print "Files in", folder, "is being populated to a list"
	if ext == "":
		ext = "/*.*"
	else:
		ext = "/*" + ext
	for file in glob.glob(folder + ext):
	# retrieves the stats for the current file as a tuple
	# (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
	# the tuple element mtime at index 8 is the last-modified-date
		filelist.append(file)
	return filelist
	print "\nFile List Prepared, starting to list them......\n"
"""-----------------------------------------------------------------------------
# Main Script
-----------------------------------------------------------------------------"""
# Select Folder
inFolder = BrowseDir("Select folder to process","C:/OES/PaleoBathymetry/Projected Shapes/diced/")
pflist=[]
pflist = getFileList(inFolder,"PseudoPoints.shp")

for pfl in pflist:
	print (time.asctime(time.localtime(time.time())))
	inFC = pfl							# BrowseFile("Select PseudoPoint Shapefile","C:/OES/PaleoBathymetry/Projected Shapes/diced/","shp")
	print "\nprocessing ", pfl
	lineno = (os.path.basename(inFC)).replace("_PseudoPoints.shp","")
	fieldList = arcpy.ListFields(inFC)
	if not "D2WS" in fieldList:
		arcpy.AddField_management(inFC,"D2WS","DOUBLE")
	if not "D2EN" in fieldList:
		arcpy.AddField_management(inFC,"D2EN","DOUBLE")
	nFC = "C:/OES/PaleoBathymetry/Projected Shapes/Step9COut_TPWS_ps.shp" #BrowseFile("Select NearFeature (WSTP) Shapefile","C:/OES/PaleoBathymetry/Projected Shapes/","shp")
	lineFC = inFC.replace("PseudoPoints.shp","XSL.shp")
	count = arcpy.GetCount_management(inFC)
	c = int(count.getOutput(0))
	print "\nNo of points = ", str(c)
	# Make a feature layer
	try:
		t = t + 1
	except:
		t = 0
	fl = "FL" + str(t)
	arcpy.MakeFeatureLayer_management (inFC, fl)
	i = 0
	while i<c:
		D2EN = -999.99
		D2WS = -999.99
		# Select a pseudopoint
		where_clause = "\"FID\" = " + str(i)
		arcpy.SelectLayerByAttribute_management (fl, "NEW_SELECTION", where_clause)
		# Create a linefile name for split
		outFC = DirCheck(DirCheck(inFC)+ lineno + "_split") + str(i).zfill(4) + ".shp"
		# Perform Split
		arcpy.SplitLineAtPoint_management (lineFC, fl, outFC)
		# Add length
		arcpy.AddField_management(outFC,"Length","DOUBLE")
		arcpy.CalculateField_management(outFC, "Length", "!Shape!.length","PYTHON_9.3","")
		# Near Analysis to WS TP
		arcpy.Near_analysis (outFC, nFC)
		# Create a search cursor for outFC
		rows = arcpy.SearchCursor(outFC)
		for row in rows:
			distance = row.getValue("NEAR_DIST")
			distance = round(distance,5)
	##		print distance
			if distance == 0:
				D2WS = row.getValue("Length")
				if D2WS == -999.99:
					D2WS = 0.0
			else:
				D2EN = row.getValue("Length")
				if D2EN == -999.99:
					D2EN = 0.0
		# Delete outFC
		arcpy.Delete_management(outFC)
		# Calculate D2EN & D2WS
		arcpy.CalculateField_management(fl, "D2EN", D2EN,"PYTHON_9.3","")
		arcpy.CalculateField_management(fl, "D2WS", D2WS,"PYTHON_9.3","")
		i = i + 1
	print (time.asctime(time.localtime(time.time())))
##	# Clear Split Folder
##	delfilelist = getFileList(os.path.dirname(outFC),"")
##	for f in delfilelist:
##		os.remove(f)
"""-----------------------------------------------------------------------------
# End Time
-----------------------------------------------------------------------------"""
EndTime = time.asctime(time.localtime(time.time()))
print "\nEnd Time: ", EndTime,"\n"
