#-------------------------------------------------------------------------------
# Name:		DrawPerpendicular.py
# Purpose:
#http://ceg-sense.ncl.ac.uk/geoanorak/code/pythontransects.html
#
# Author:		Dr. Arghya Goswami
# Contact:		arghya.goswami@gmail.com
#
# Created:		14/03/2014
#
# Copyright:		(c) Dr. Arghya Goswami 2014
#
# 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 Tkinter import *
##from arcpy.sa import *
if arcpy.CheckExtension("3D") == "Available":
	arcpy.CheckOutExtension("3D")
if arcpy.CheckExtension("GeoStats") == "Available":
	arcpy.CheckOutExtension("GeoStats")
if arcpy.CheckExtension("Spatial") == "Available":
	arcpy.CheckOutExtension("Spatial")
"""-----------------------------------------------------------------------------
# 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
	elif ext == "cdf":
		desc1 = "Common Data Format 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

def AllfFields(infile):
	global 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"
	global 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)
	print "\nFile List Prepared, starting to list them......\n"
"""-----------------------------------------------------------------------------
# Main Script
-----------------------------------------------------------------------------"""
# Search Cursor
inFC = BrowseFile("Select Shapefile","C:/","shp")

outFCSh = DirCheck(os.path.dirname(inFC))+(os.path.basename(inFC)).replace(".shp","_ShPoints.shp")
outFCAR = DirCheck(os.path.dirname(inFC))+(os.path.basename(inFC)).replace(".shp","_ARPoints.shp")

ShPtGeomeLst = []
rPtGeomeLst = []

for row in arcpy.da.SearchCursor(inFC, ["OID@","SHAPE@","Dist2M","PDist","ShelfW","SlopeW","RiseW","LineLength"]):
	# Print the current line ID
	print("Processing Feature {0}:".format(row[0]))

	#Set Shelf-Slope point
	shpt = arcpy.Point()
	shpt = row[1].positionAlongLine(row[4]/row[7],TRUE).firstPoint
	ShPtGeom = arcpy.PointGeometry(shpt)
	ShPtGeomeLst.append(ShPtGeom)

	#Set Slope-Rise point
	rpt = arcpy.Point()
	rpt = row[1].positionAlongLine(row[3]/row[7],TRUE).firstPoint
	rPtGeom = arcpy.PointGeometry(rpt)
	rPtGeomeLst.append(rPtGeom)

del row

arcpy.CopyFeatures_management(ShPtGeomeLst, outFCSh)
arcpy.CopyFeatures_management(rPtGeomeLst, outFCAR)

"""-----------------------------------------------------------------------------
# End Time
-----------------------------------------------------------------------------"""
EndTime = time.asctime(time.localtime(time.time()))
print "\nEnd Time: ", EndTime,"\n"
