# Batch and Schedule a Geoprocessing Script, Python v3.x
# Created by: Nathan Jennings
#             urbandalespatial.com
# Created on: 05.24.2011
# Update on: 01.13.2022
# Copyright: 2011, 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
    with open(logfile, 'a') as log:
    
    

        print ('Running Clip Routine...')
        print ('Running Clip Routine...', file=log)
        print ('Input workspace is: ' + arcpy.env.workspace)
        print ('Input workspace is: ' + arcpy.env.workspace, file=log)
        print ('Input file is: ' + infile)
        print ('Input file is: ' + infile, file=log)
        print ('Clip file is: ' + clipfile)
        print ('Clip file is: ' + clipfile, file=log)
        print ('Output workspace is: ' + output_ws)
        print ('Output workspace is: ' + output_ws, file=log)
        print ('Output file is: ' + outfile)
        print ('Output file is: ' + outfile, file=log)

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

        print ('Completed Clip')
        print ('Completed Clip', file=log)

    log.close()

except:
    # https://pro.arcgis.com/en/pro-app/arcpy/get-started/error-handling-with-python.htm
    
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
    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))
