"""
 Tool Name:  DownloadNHD
 Description: Downloads NHD data by HUC4 using the National Map API.
 Author: Patrick Longley (plongley@usgs.gov)
 Created: 08/11/2020
 Language: Written in python3 (arcpro). Modified to also work in python2 (arcmap).
 History:
"""

# IMPORTS
import os
import arcpy
import sys
import wbd_f
import wbd_params

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

class DownloadNHD(object):
    """
    Downloads NHD data by HUC4 using the National Map API.

    Args:
        huc (str): HUC code (more than one can be entered.)
        out_folder (str):  Output folder where data will be saved.
        spatial_reference (ESRI spatial reference object): Spatial reference data will be saved in.
        
    Outputs:
        returns: nhd_fd_rpj
        output parameter: New NHD geodatabase is created.

    """
    
    def __init__(self):
        """
        Initialize variables
        """
        self.label       = "Download NHD data"
        self.description = "This tool downloads NHD data by HUC4 " + \
                           "using the national map api."
        self.callfrom_pyt = True
        self.category = 'Download data'

    def getParameterInfo(self):
        """
        Define the parameters for use in arcmap/pro.
        """
        if python_version == 3:
            huc = wbd_params.huc_py3
        elif python_version == 2:
            huc = wbd_params.huc_py2
        params = [huc,
                  wbd_params.out_folder,
                  wbd_params.spatial_reference]
        return params

    def updateMessages(self, params):
        """
        Modify the messages created by internal validation for each tool
        parameter.This method is called after internal validation. 
        """
        if params[0].value and params[0].altered and params[0].value!='':
            huclist = params[0].valueAsText.replace(" ", "").split(';')
            c1 = wbd_f.check_huc4(huclist)
            if not c1:
                message = 'Invalid HUC code(s).'
                params[0].setErrorMessage(message)

    def execute(self, params, messages):
        """
        Loops through HUCS and downloads NHD data.
        """
        # parameters
        if self.callfrom_pyt:
            self.hucs = params[0].valueAsText
            self.out_folder = params[1].valueAsText
            self.sr = params[2].valueAsText
        else:
            self.hucs = params[0]
            self.out_folder = params[1]
            self.sr = params[2]
        self.hucs = self.hucs.replace(" ", "").split(';')

        fd_name = 'Hydrography'
        for huc in self.hucs:
            huc4 = huc[:4]
            url = 'https://prd-tnm.s3.amazonaws.com/StagedProducts/Hydrography/NHD/HU4/' + \
                  'HighResolution/GDB/NHD_H_{}_HU4_GDB.zip'.format(huc4)
            nhd_fd = wbd_f.download_fd(self.out_folder, url, fd_name)
            # delete hydronet junctions
            arcpy.Delete_management(os.path.join(nhd_fd, 'HYDRO_NET'))
            arcpy.Delete_management(os.path.join(nhd_fd, 'HYDRO_NET_Junctions'))
            arcpy.Delete_management(os.path.join(os.path.dirname(nhd_fd), 'WBD'))
            # reproject
            nhd_fd_rpj = wbd_f.reproject_fd(nhd_fd, self.sr)
        return nhd_fd_rpj

if __name__ == '__main__':
    """
    Execute as standalone script.
    """
    hucs = '1801;1901'
    output_folder = r'C:\Users\plongley\Downloads'
    params = (hucs, output_folder, None)
    download_nhd = DownloadNHD()
    download_nhd.callfrom_pyt = False
    download_nhd.execute(params, None)