"""
 Tool Name:  DownloadWBD
 Description: Downloads WBD data by HUC2 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 sys
import wbd_f
import wbd_params

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

class DownloadWBD(object):
    """
    Downloads WBD data by HUC2 using the National Map API.

    Args:
        huc (str): HUCs seperated by semicolons,
        out_folder (str): Folder where outputs are saved.
        spatial_reference (ESRI spatial reference object): Spatial reference data will be saved in.

    Outputs:
    returns: wbd_fd_rpj (feature datasets):  WBD feature datasets
    output parameter: New WBD geodatabase is created.

    """
    def __init__(self):
        """
        Initialize variables
        """
        self.label       = "Download WBD data"
        self.description = "This tool downloads WBD data by HUC2 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 != '':
            try:
                huclist = params[0].valueAsText.replace(" ", "").split(';')
            except AttributeError:
                pass
            c1 = wbd_f.check_hucre(huclist)
            if not c1:
                message = 'Invalid HUC code(s).'
                params[0].setErrorMessage(message)

    def execute(self, params, messages):
        """
        Loops through HUCS and downloads WBD 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 = 'WBD'
        for huc in self.hucs:
            huc2 = huc[:2]
            url = 'https://prd-tnm.s3.amazonaws.com/StagedProducts/Hydrography/WBD/HU2/GDB/WBD_{}_HU2_GDB.zip'.format(huc2)
            wbd_fd = wbd_f.download_fd(self.out_folder, url, fd_name)
            wbd_fc = os.path.join(wbd_fd,'WBDHU' + str(len(huc)))
            # reproject
            wbd_fd_rpj = wbd_f.reproject_fd(wbd_fd, self.sr)
        return wbd_fd_rpj

if __name__ == '__main__':
    """
    Execute as standalone script.
    """
    hucs = '18;19'
    output_folder = r'C:\Users\plongley\Downloads'
    params = (hucs, output_folder, None)
    download_wbd = DownloadWBD()
    download_wbd.callfrom_pyt = False
    download_wbd.execute(params, None)


