"""
 Tool Name:  DownloadWorkflow
 Description: Downloads WBD, NHD, and 3DEP data using the National map API
              and the Alaska data portal.  Pacakges data for WBD work.
 Author: Patrick Longley (plongley@usgs.gov)
 Created: 08/11/2020
 Language: Written in python3 (arcpro). Modified to also work in python2 (arcmap).
 History:
 TODO: set output symbology (tried several approaches nothing worked).  May need to use feature layers not feature classes...
"""

# IMPORTS
import os
import sys
import wbd_f
import wbd_params
import download_wbd
import download_nhd
import download_3dep
import download_packagedata

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

LAYER_FOLDER = os.path.join(
    os.path.dirname(
        os.path.dirname(
            os.path.abspath(__file__)
        )
    ), os.path.join('layer_files', 'usgs')
)

class DownloadWorkflow(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.
        dataset_3dep (str): 3DEP dataset that will be downloaded.        
        buffer_dist (str): Buffer distance for DEM.  
        contour_spacing (int): Contour spacing
        include_artificial (boolean): Include ditches and canals in NHD flowline featureclass?

    Outputs:
        returns: None
        dem_out (raster):  Copy of DEM.

    """
    def __init__(self):
        """
        Initialize variables
        """
        self.label       = "Download workflow"
        self.description = "This tool combines the Download_wbd, Download_nhd, " + \
                           "Download_3dep, and Package_data tools."
        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,
            wbd_params.dataset_3dep,
            wbd_params.buffer_dist,
            wbd_params.contour_spacing,
            wbd_params.include_artificial,
        ]
        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 updateParameters(self, params):
        """
        Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parmater
        has been changed.
        """
        if not params[0].value or params[0].value == '':
            params[3].filter.list = wbd_params.dataset_3dep.filter.list
        elif params[0].altered:
            huclist = params[0].valueAsText.replace(" ", "").split(';')
            huc2s = [x[:2] for x in huclist]
            params[3].filter.list = wbd_f.modify_3depchoices(huc2s, params[3].filter.list)

    def execute(self, params, messages):
        """
        Loops through a list of HUCS and:
        1) downloads WBD, NHD, and 3DEP data for each HUC.
        2) packages the data for WBD work.
        """
        # define tool classes
        downloadwbd = download_wbd.DownloadWBD()
        downloadnhd = download_nhd.DownloadNHD()
        download3dep = download_3dep.Download3DEP()
        package_data = download_packagedata.PackageData()
        # tools not called from UI
        downloadwbd.callfrom_pyt = False
        downloadnhd.callfrom_pyt = False
        download3dep.callfrom_pyt = False
        package_data.callfrom_pyt = False
        # parameters
        if self.callfrom_pyt:
            self.hucs = params[0].valueAsText
            self.out_folder = params[1].valueAsText
            self.sr = params[2].valueAsText
            self.dataset_3dep = params[3].valueAsText
            self.buffer_dist = params[4].valueAsText
            self.contour_spacing = params[5].valueAsText
            self.include_artificial = params[6].value
        else:
            self.hucs = params[0]
            self.out_folder = params[1]
            self.sr = params[2]
            self.dataset_3dep = params[3]
            self.buffer_dist = params[4]
            self.contour_spacing = params[5]
            self.include_artificial = params[6]
        self.huclist = self.hucs.replace(" ", "").split(';')
        # loop through the inputed hucs
        for huc in self.huclist:
            # download wbd
            wbd_params = [huc, self.out_folder, self.sr]
            wbd_fd_rpj = downloadwbd.execute(wbd_params, None)
            # download nhd
            nhd_params = [huc, self.out_folder, self.sr]
            nhd_fd_rpj = downloadnhd.execute(nhd_params, None)
            # package data
            package_params = [
                huc,
                wbd_fd_rpj,
                nhd_fd_rpj,
                self.out_folder,
                self.contour_spacing,
                self.include_artificial,
            ]
            self.prep_folder = package_data.execute(package_params, None)
            # download 3dep
            if self.dataset_3dep:
                dem_params = [
                    huc,
                    self.prep_folder,
                    self.sr,
                    self.dataset_3dep,
                    self.buffer_dist,
                    self.contour_spacing,
                ]
                download3dep.execute(dem_params, None)




if __name__ == '__main__':
    """
    Execute as standalone script.
    """
    hucs = '180101010101;170101010101'
    output_folder = r'C:\Users\plongley\Downloads'
    sr = None
    dataset_3dep = 'National Elevation Dataset (NED) 1 arc-second'
    buffer_dist = '1000 Meters'
    contour_spacing = 100
    include_artificial = False
    params = (hucs, output_folder, sr, dataset_3dep, buffer_dist, contour_spacing, include_artificial)
    download_workflow = DownloadWorkflow()
    download_workflow.callfrom_pyt = False
    download_workflow.execute(params, None)