#-------------------------------------------------------------------------------
# Name:			Sediment Wedge Model Generator Aug 2013 Part II.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
-----------------------------------------------------------------------------"""
ptFileList = []
lineFileList = []
NormalDistList = []

inDir = BrowseDir("Select directory","C:/OES/PaleoBathymetry/Projected Shapes/diced/")
etptFileList = getFileList(inDir,"_LineETPoints.shp")
lineFileList = getFileList(inDir,"_XSectionLine.shp")
NormalDistList = getFileList(inDir,"_Normals2XSectionLine.shp")

noLines = len(etptFileList)
print "No of Lines to process in this SET = ", str(noLines)

""" Step 8: """
c =0
while c < noLines:
	print "\n###################################################\nProcessong LineNo: "+ os.path.basename(etptFileList[c])[:3] + ".......\n###################################################\n"
	# Spatially join et & normal distance shapefiles
	outETNDist = (NormalDistList[c]).replace(".shp","ET.shp")
	arcpy.SpatialJoin_analysis (NormalDistList[c], etptFileList[c], outETNDist)
	fList = AllFields(outETNDist)
	for fdName in fList:
		if fdName == "FID" or fdName == "Shape" or fdName == "LON" or fdName == "LAT" or fdName =="ET1" or fdName == "ET5":
			pass
		else:
			arcpy.DeleteField_management(outETNDist,fdName)
	del fList,fdName

	# Intersect to get PseudoPoints Shapefiles
	in_features = []
	in_features.append(lineFileList[c])
	in_features.append(outETNDist)
	outPseudoFC = DirCheck(os.path.dirname(etptFileList[c])) + (os.path.basename(etptFileList[c])).replace("LineETPoints.shp","PseudoPoints.shp")
##	print outPseudoFC
	arcpy.Intersect_analysis (in_features, outPseudoFC, "ALL", "", "POINT")
	# Count No of PseudoPoints
	print "No of Pseudo Points = " + str(arcpy.GetCount_management(outPseudoFC))
	fList = AllFields(outPseudoFC)
	for fdName in fList:
		if "FID_" in fdName:
			arcpy.DeleteField_management(outPseudoFC,fdName)
	del fList,fdName

	# Duplicate Line with no attributes
	outXSL = (lineFileList[c]).replace("XSectionLine.shp","XSL.shp")
	arcpy.Copy_management(lineFileList[c], outXSL)
	fList = AllFields(outXSL)
	for fdName in fList:
		if fdName == "FID" or fdName == "LineID"or fdName == "Shape":
			pass
		else:
			arcpy.DeleteField_management(outXSL,fdName)
	del fList,fdName

	# Split each line on the psedupoints
	i = 1
	rows = arcpy.SearchCursor(outPseudoFC)
	for row in rows:
		outFC = DirCheck(DirCheck(outPseudoFC)+ "split") + str(i).zfill(4) + ".shp"
		arcpy.SplitLineAtPoint_management(outXSL, outPseudoFC, outFC)
		i = i + 1
	del row
	del rows
	print "Split files ready!"

	# get the list of shapefile names of the split folder
	splitList = getFileList(os.path.dirname(outFC),"shp")

	# perform merge
	mergedFC = DirCheck(outPseudoFC) + (os.path.basename(outPseudoFC))[:3] + "_MergedSplitLines.shp"
	print "No of files to merge = ", len(splitList)
	arcpy.Merge_management(splitList, mergedFC)
	print "Split files merged"

	# Calculate Lengths
	arcpy.AddField_management (mergedFC, "Length", "DOUBLE")
	arcpy.CalculateField_management(mergedFC, "Length", "!Shape!.length","PYTHON_9.3","")
	print "Length calculated..."

	# Delete ID field
	arcpy.DeleteField_management(mergedFC,"ID")

	# Clear Split Folder
	filelist = getFileList(os.path.dirname(outFC),"")
	for f in filelist:
		os.remove(f)

	c = c + 1


"""	Step 9
	1) Manually add the west terminal points of set 16
	2) """
"""-----------------------------------------------------------------------------
# End Time
-----------------------------------------------------------------------------"""
EndTime = time.asctime(time.localtime(time.time()))
print "\nEnd Time: ", EndTime,"\n"