# Batch and Schedule a Geoprocessing Script
# Created by: Nathan Jennings
#             urbandalespatial.com
# Created on: 05.24.2011
# Update on: 01.02.2016
# Copyright: 2016, UrbandaleSpatial

'''
!!!!  Change the output and log file paths as needed where the Chapter 12 folders exist.!!!

Save these changes.  Test the script to make sure it executes properly.
'''


import arcpy, sys, os, traceback, datetime

CURDATE = datetime.date.today()

try:

    # workspace for input data
    # e.g c:\\pythonprimer\\chapter12\\data
    arcpy.env.workspace = arcpy.GetParameterAsText(0)

    # name of input shapefile feature class to be clipped
    # i.e. city_facilities.shp
    infile = arcpy.GetParameterAsText(1)

    # name of clip shapefile feature class to use as the clip file
    # i.e. central_city_commplan.shp
    clipfile = arcpy.GetParameterAsText(2)

    # output folder name for output
    # e.g. c:\\pythonprimer\\chapter12\\mydata
    output_ws = arcpy.GetParameterAsText(3)
    
    # name of the output feature class
    # concatenate the workspace (i.e. folder) with the name of the output file name    
    outfile = os.path.join(output_ws, arcpy.GetParameterAsText(4))

    # location of log file for tracking messages
    logfile = output_ws + '\\log' + str(CURDATE) + '.txt' 

    if arcpy.Exists(logfile):
        arcpy.Delete_management(logfile)

    # Open the log file for writing
    log = open(logfile, 'a')
    
    

    print '\nRunning Clip Routine...'
    print >> log, 'Running Clip Routine...'
    print 'Input workspace is: ' + arcpy.env.workspace
    print >> log, 'Input workspace is: ' + arcpy.env.workspace
    print 'Input file is: ' + infile
    print >> log, 'Input file is: ' + infile
    print 'Clip file is: ' + clipfile
    print >> log, 'Clip file is: ' + clipfile
    print 'Output workspace is: ' + output_ws
    print >> log, 'Output workspace is: ' + output_ws
    print 'Output file is: ' + outfile
    print >> log, 'Output file is: ' + outfile

    if arcpy.Exists(outfile):
        arcpy.Delete_management(outfile)
        
    arcpy.Clip_analysis(infile, clipfile, outfile)

    print 'Completed Clip'
    print >> log, 'Completed Clip'

    log.close()

except:
    print arcpy.GetMessages(2)
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n     " +        str(sys.exc_type) + ": " + str(sys.exc_value) + "\n"
    msgs = "arcpy ERRORS:\n" + arcpy.GetMessages(2) + "\n"

    arcpy.AddError(msgs)
    arcpy.AddError(pymsg)

    print msgs
    print pymsg
    
    arcpy.AddMessage(arcpy.GetMessages(1))
    print arcpy.GetMessages(1)

