# Template script for a an ArcPy script tool using egis.py
# Shows how to use the egis module to trap errors,
# manage messages, and handle scratch files.
#
# Use this script as a starting point for your own scripting using the egis module.
# The egis module has many useful methods, to see them all:
# >>> import egis;help(egis)

# History:
# Clarence King, cking@usgs.gov, 1879-03-03, original coding
# Curtis Price, cprice@usgs.gov, 2011-10-12 arcpy compatibility; fixes
# Curtis Price, 2011-11-15 updated exception handling
# Curtis Price, 2014-05-01 updated exception handling to work with python 3x
# Curtis Price, 2014-11-14 tool encapsulated in function
# Curtis Price, 2019-06-21 updated to support python 2/3

# Python 3.x compatibility for Pro
from __future__ import print_function, unicode_literals, absolute_import

import sys
import os
import traceback
import arcpy
## arcpy.CheckOutExtension("spatial") # spatial analyst license
## from arcpy.sa import * # for ArcPy map algebra
import egis
from egis import GPMsg, MsgError

def test_tool(arg1=None, arg2=None):
    """Example script tool using egis.py module

    Template tool output:

    Executing: RunTemplate hello world
    Start Time: Fri Jun 21 12:59:18 2019
    Running script RunTemplate...
    [u'hello', u'world']
    If this you see this, there were no errors!
    This is warning, just to keep you on your toes.
    WARNING 000732: tmpGrid: Dataset tmpGrid1 does not exist or is not supported
    12:59:18 00.22 Now is the time for all good persons...
    Completed script RunTemplate...
    Succeeded at Fri Jun 21 12:59:18 2019 (Elapsed Time: 0.24 seconds)"""
    try:
        # Print arguments
        GPMsg(repr([arg1, arg2]))

        # egis.ScratchName method gets valid scratch names
        tmpGrid = egis.ScratchName("","","grid")

        # Three different kinds of errors
        # (uncomment one at a time to see how they get handled)

        # 1. Script-raised error - send a message to user
        #raise MsgError("Your data have issues")
        # 2. runtime Python error, divide by zero
        #x = 3 / 0
        # 3. ESRI Geoprocessing error (tmpGrid doesn't exist)
        #Result = arcpy.GetCount_management("tmpGrid")

        GPMsg("If this you see this, there were no errors!")
        GPMsg("w", "This is warning, just to keep you on your toes.")
        # ArcGIS geoprocessing message w/ args
        GPMsg("w", "ID 732 {}|{}".format("tmpGrid","tmpGrid1"))
        # script timer
        GPMsg("t", "Now is the time for all good persons...")

    except MsgError as xmsg:
        GPMsg("e", str(xmsg))
    except arcpy.ExecuteError:
        tbinfo = traceback.format_tb(sys.exc_info()[2])[0]
        GPMsg("e", tbinfo.strip())
        for i in range(arcpy.GetMessageCount()):
            GPMsg("r", i) # use AddReturnMessage()
    except Exception as xmsg:
        # generic python errors
        tbinfo = traceback.format_tb(sys.exc_info()[2])[0]
        GPMsg("e", tbinfo.strip())
        GPMsg("e", str(xmsg))
    finally:
        # Clean up here (delete cursors, temp files)
        pass

if __name__ == "__main__":
    # Script tool interface:
    # Get zero or more parameters as text, call tool
    argv = tuple(arcpy.GetParameterAsText(i)
        for i in range(arcpy.GetArgumentCount()))
    test_tool(*argv)
