""" 
 Tool Name:  SubwatershedLines
 Description: Performs subwatershed delineation and copies data.
 Author: Patrick Longley (plongley@usgs.gov)
 Created: 09/17/2020
 Language: Written in python3 (arcpro). Does not work in python2 (arcmap).
 History: 
    20201006 metadata, 
    20201006 constants, 
    20201006 check fields in validation (not needed)
    10/14/2020 general review
 TODO: Output to map
 TODO: Could automatically remove small lines. 
        3 vertices/short >>> remove middle vertex, then delete identical shape
        5 vertices/startpoint = endpoint >>> square/delete,
        dongle >>> delete
 TODO: this script currently does nothing as a standalone script (no error, just stops during archydro initialization)
"""
import os
import sys
import arcpy
import wbd_params
import wbd_f
import wbd_c
import geometry_createtopology
# ARCHydro tools
from archydro.subwatersheddelineation import SubwatershedDelineation


#PYTHON 2/3 issues
python_version = sys.version_info.major

class SubwatershedLines(object):
    def __init__(self):
        """
        Initialize variables
        """
        self.label       = "2) Subwatershed Lines"
        self.description = "Subwatershed delineation"
        self.callfrom_pyt = True
        self.category = 'Elevation derived hydrography'

    def getParameterInfo(self):
        """
        Define the parameters for use in arcmap/pro.
        """
        params = [
            wbd_params.batch_points,
            wbd_params.fdr,
            wbd_params.str_ras,
        ]
        return params

    def initialize_archydrotools(self):
        self.subwatersheddelineation = SubwatershedDelineation()
        self.subwatersheddelineation.bCallFromPYT = False
        
    def execute(self, params, messages):
        """
        Performs archydro terrain preprocessing
        """
        arcpy.env.parallelProcessingFactor = "100%"
        # parameters
        if self.callfrom_pyt:
            self.batch_points = params[0].valueAsText
            self.fdr = params[1].valueAsText
            self.str_ras = params[2].valueAsText
        else:
            self.batch_points = params[0]
            self.fdr = params[1]
            self.str_ras = params[2]
        self.wbdline_template = wbd_c.WBDLINE_TEMPLATE

        self.initialize_archydrotools()
        self.fdpath, self.dbpath, self.raster_folder = wbd_f.ah_workspaces(python_version, self.callfrom_pyt)

        # Subwatershed delineation
        _, subwatershed, _ = self.subwatersheddelineation.execute([self.batch_points,
                                                                   0,
                                                                   self.fdr,
                                                                   self.str_ras,
                                                                   os.path.join(self.fdpath, wbd_c.SUBWATERSHED),
                                                                   os.path.join(self.fdpath, wbd_c.SUBWATERSHEDPOINTS)],
                                                                  None)
        arcpy.AddField_management(subwatershed, 'Acres', 'DOUBLE')
        arcpy.CalculateField_management(subwatershed, 'Acres', "!shape.area@acres!", "PYTHON", "")
        arcpy.AddField_management(subwatershed, 'Notes', 'TEXT', field_length=250)
        arcpy.CopyFeatures_management(subwatershed, os.path.join(self.fdpath, wbd_c.SUBWATERSHEDBACKUP))

        # Polygon to line
        subwatershed_line = arcpy.PolygonToLine_management(subwatershed, os.path.join(self.fdpath, wbd_c.SUBWATRESHEDLINE))

        # Smooth/Simplify
        subwatershed_smooth = arcpy.cartography.SmoothLine(subwatershed_line, os.path.join(self.fdpath, wbd_c.SUBWATERSHEDPAEK10), "PAEK", 10)
        subwatershed_simplify = arcpy.cartography.SimplifyLine(subwatershed_smooth, os.path.join(self.fdpath, wbd_c.SUBWATERSHEDPOINTREMOVE5), "POINT_REMOVE", 5)
        newlines = arcpy.CreateFeatureclass_management(self.fdpath, wbd_c.NEWLINES, template=self.wbdline_template)
        arcpy.Append_management(subwatershed_simplify, newlines, "NO_TEST")
        arcpy.AddField_management(newlines, 'Comments', 'TEXT', field_length=250)
        arcpy.AddField_management(newlines, 'Status', 'TEXT', field_length=30)

        # create topology
        createtopology = geometry_createtopology.CreateTopology()
        createtopology.callfrom_pyt = False
        createtopology.execute((newlines[0], None), None)


if __name__ == '__main__':
    """
    Execute as standalone script.
    """
    # set workspace to prevent this script from saving in the scratch database in an inconvenient location
    arcpy.env.workspace = r'C:\GIS_Project\WBD\AK\Work\hu19080305\19080305_proj.gdb'
    batch_points = r'C:\GIS_Project\WBD\AK\Work\hu19080305\19080305_prep\19080305_data.gdb\initial_data\batch_points'
    fdrstradj = r'C:\GIS_Project\WBD\AK\Work\hu19080305\Layers\fdrstradj'
    strlnk = r'C:\GIS_Project\WBD\AK\Work\hu19080305\Layers\strlnk'
    linetemplate = r'C:\GIS_Project\WBD\WatershedCreation_Docs\WBD_Template_alb.gdb\Line'
    params = (batch_points, fdrstradj, strlnk)
    subwatershed_line = SubwatershedLines()
    subwatershed_line.callfrom_pyt = False
    subwatershed_line.execute(params, None)



