# coding: utf-8
#

# Esri start of added variables
g_ESRI_variable_1 = r'%scratchGDB%\tempSortedPoints'
# Esri end of added variables

#

#------------------------------------------------------------------------------
# Copyright 2015 Esri
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#------------------------------------------------------------------------------
#
# ==================================================
# NumberFeatures.py
# --------------------------------------------------
# Built on ArcGIS
# ==================================================
#
# This tool will number features within a point feature class spatially from left to right,
# top to bottom for a selected area.
#
# ==================================================
# HISTORY:
#
# 8/25/2015 - mf - Needed to update script for non-ArcMap/Pro testing environment
#
# ==================================================

import os, sys, math, traceback
import arcpy
from arcpy import env
from arcpy import sa
import Utilities

# Read in the Parameters
areaToNumber = arcpy.GetParameterAsText(0)
pointFeatures = arcpy.GetParameterAsText(1)
numberingField = arcpy.GetParameterAsText(2)
outputFeatureClass = arcpy.GetParameterAsText(3)

DEBUG = True
appEnvironment = None
mxd, df, aprx, mp, mapList = None, None, None, None, None

def labelFeatures(layer, field):

    ''' set up labeling for layer '''
    if appEnvironment == "ARCGIS_PRO":
        if layer.supports("SHOWLABELS"):
            for lblclass in layer.listLabelClasses():
                lblclass.visible = True
                lblclass.expression = "$feature.Number"
            layer.showLabels = True
    elif appEnvironment == "ARCMAP":
        if layer.supports("LABELCLASSES"):
            for lblclass in layer.labelClasses:
                lblclass.showClassLabels = True
                lblclass.expression = " [" + str(field) + "]"
            layer.showLabels = True
            arcpy.RefreshActiveView()
    else:
        pass # if returns "OTHER"

def findLayerByName(layerName):
    #UPDATE
    if appEnvironment == "ARCGIS_PRO":
    #if gisVersion == "1.0": #Pro:
        if DEBUG == True:
            arcpy.AddMessage("Pro labeling for " + layerName + "...")
        for layer in mapList.listLayers():
            if layer.name == layerName:
                arcpy.AddMessage("Found matching layer [" + layer.name + "]")
                return layer
            else:
                arcpy.AddMessage("Incorrect layer: [" + layer.name + "]")

    #else:
    elif appEnvironment == "ARCMAP":
        if DEBUG == True: arcpy.AddMessage("Map labeling for " + layerName + "...")

        for layer in arcpy.mapping.ListLayers(mxd):
            if layer.name == layerName:
                arcpy.AddMessage("Found matching layer [" + layer.name + "]")
                return layer
            else:
                arcpy.AddMessage("Incorrect layer: [" + layer.name + "]")
    else:
        arcpy.AddMessage("Non-map environment, no layers to find...")


def GetApplication():
    '''Return app environment as ARCMAP, ARCGIS_PRO, OTHER'''
    try:
        from arcpy import mp
        return "ARCGIS_PRO"
    except ImportError:
        try:
            from arcpy import mapping
            mxd = arcpy.mapping.MapDocument("CURRENT")
            return "ARCMAP"
        except:
            return "OTHER"



def main():
    ''' main '''
    #UPDATE
    # Create a feature layer from the input point features if it is not one already
    #df = arcpy.mapping.ListDataFrames(mxd)[0]
    pointFeatureName = os.path.basename(pointFeatures)
    layerExists = False

    try:
        # Check that area to number is a polygon
        descArea = arcpy.Describe(areaToNumber)
        areaGeom = descArea.shapeType
        arcpy.AddMessage("Shape type: " + str(areaGeom))
        if (descArea.shapeType != "Polygon"):
            raise Exception("ERROR: The area to number must be a polygon.")

        gisVersion = arcpy.GetInstallInfo()["Version"]
        global appEnvironment
        appEnvironment = Utilities.GetApplication()
        if DEBUG == True: arcpy.AddMessage("App environment: " + appEnvironment)

        global mxd
        global df
        global aprx
        global mp
        global mapList
        # mxd, df, aprx, mp = None, None, None, None
        #if gisVersion == "1.0": #Pro:
        if appEnvironment == "ARCGIS_PRO":
            from arcpy import mp
            aprx = arcpy.mp.ArcGISProject("CURRENT")
            mapList = aprx.listMaps()[0]
            for lyr in mapList.listLayers():
                if lyr.name == pointFeatureName: