# import matplotlib.pyplot as plt
import os
import numpy as np
import gdal_merge as gm
#import lib.gdal_merge as gm
import sys

import argparse

#https://lists.osgeo.org/pipermail/gdal-dev/2016-August/045083.html

#sys.path.insert(0,'C:\Users\rhussain\lsrd_pycharm_projects\UHI\lib')
#import gdal_merge as gm

#sys.path.insert(0, 'C:\ProgramData\Anaconda3\pkgs\gdal-2.3.3-py36hdf43c64_0\Scripts')
#import gdal_merge as gm
# from osgeo import ogr, gdal

def merge_files(gm, file_list, outDir, outName_list):

    if not os.path.exists(outDir):
        os.mkdir(outDir)
    # outDir = r'H:\qzhou\Therm_ARD'
    for files, outName in zip(file_list, outName_list):
        print('Processing: ', outName)

        all_files_present = True
        for file in files:
            if not os.path.exists(file):
                print(file + " is missing")
                ABC = None
                all_files_present = False

        if not all_files_present:
            continue

        #if not np.all([os.path.exists(file) for file in files]):
        #    print('Some tiles are missing!')
        #    continue

        # merge_command = ["python", gm, "-o", os.path.join(outDir, outName)]
        # merge_command.extend(files)
        # print(merge_command)
        # subprocess.run(merge_command, shell=True)

        merge_command = ['', "-o", os.path.join(outDir, outName),'-a_nodata',"-9999"]
        merge_command.extend(files)
        ABC = None
        gm.main(merge_command)
        ABC2 = None


def merge_batch_forHua(work_path,HV_List,start_year_inclusive,end_year_inclusive,iata_location_identifier):


    #root = r'S:\Temp\Shi\Impervious_surface\UHI\data\siouxfalls'
    #HV_list = ['H16V06']
    #start_year = 1984
    #end_year = 2019

    #official
    #root = r'C:\Users\rhussain\Desktop\LSRD\data\atlanta'
    #HV_list = ['H23V13', 'H23V14', 'H24V13', 'H24V14']
    #start_year = 1988
    #end_year = 1990

    #test
    #root = "/caldera/projects/usgs/eros/urban_heat_islands/atlanta"
    #HV_List = ["H23V13"]
    #start_year = 1988
    #end_year = 1989

    root = work_path
    start_year = int(start_year_inclusive)
    end_year = int(end_year_inclusive)

    ######################################################################################
    '''
    new version
    so there should be the same amount of files in each location
    so we should be able to just get the filenames from the first location
    and make the paths
    then feed it into the merge function
    '''

    def merge_folder_across_tiles(folder_name):

        paths_for_identical_filenames = {}
        for HV in HV_List:
            hv_folder_path = os.path.join(root,HV,folder_name)
            file_names = os.listdir(hv_folder_path)
            for file_name in file_names:
                file_full_path = os.path.join(hv_folder_path, file_name)
                if file_name not in paths_for_identical_filenames.keys():
                    paths_for_identical_filenames[file_name] = []
                paths_for_identical_filenames[file_name].append(file_full_path)

        file_list = []
        out_name_list = []
        for i in range(len(paths_for_identical_filenames.keys())):
            key = list(paths_for_identical_filenames.keys())[i]
            out_name_list.append(key)
            file_list.append(paths_for_identical_filenames[key])
            ABC = None

        if not os.path.exists(os.path.join(root, iata_location_identifier)):
            os.mkdir(os.path.join(root, iata_location_identifier))
        outDir = os.path.join(root, iata_location_identifier, "output_folder",folder_name)

        if not os.path.exists(outDir):
            os.makedirs(outDir,exist_ok=True)

        merge_files(gm, file_list, outDir, out_name_list)

    ABC = None

    merge_folder_across_tiles("ANNUAL")
    merge_folder_across_tiles("SEASONAL")
    merge_folder_across_tiles("TOTAL")

    '''
    remove when u confirm not needed
    ######################################################################################
    annual_stats_list = [
                  'MedianT', 'MaxT', 'MeanT', 'MinT',
                  'numClear',
                  'MeanSeason1', 'MeanSeason2', 'MeanSeason3', 'MeanSeason4',
                  'MedianSeason1', 'MedianSeason2', 'MedianSeason3', 'MedianSeason4',
                  'MaxSeason1', 'MaxSeason2', 'MaxSeason3', 'MaxSeason4',
                  'MinSeason1', 'MinSeason2', 'MinSeason3', 'MinSeason4']

    for annual_stats in annual_stats_list:

        file_list = []
        outName_list = []
        for i_year in range(start_year, end_year + 1):
            temp_list = []
            if not os.path.exists(os.path.join(root, iata_location_identifier)):
                os.mkdir(os.path.join(root, iata_location_identifier))
            outDir = os.path.join(root, iata_location_identifier, annual_stats)

            #outDir = os.path.join(root, 'stats_merged')
            #if not os.path.exists(outDir):
            #    os.mkdir(outDir)
            #outDir = os.path.join(outDir, annual_stats)

            for HV in HV_List:
                inDir = os.path.join(root, HV) #, 'stats'
                temp_list.append(os.path.join(inDir, "stats","{}_{}_{}.tif".format(HV, annual_stats, i_year)))
            file_list.append(temp_list)
            outName_list.append('{}_{}.tif'.format(iata_location_identifier+"_"+annual_stats, i_year))

        merge_files(gm, file_list, outDir, outName_list)
    #############################################################################################


    ##############################################################################################


    year_range_string = str(start_year)+"-"+str(end_year)
    annual_stats_list = ['MedianT_r-squared_'+year_range_string, 'MedianT_pValue_'+year_range_string, 'MedianT_Slope_'+year_range_string,'MedianT_num_observations_'+year_range_string,
                         'MaxT_r-squared_'+year_range_string, 'MaxT_pValue_'+year_range_string, 'MaxT_Slope_'+year_range_string,'MaxT_num_observations_'+year_range_string,
                         'MeanT_pValue_'+year_range_string, 'MeanT_r-squared_'+year_range_string, 'MeanT_Slope_'+year_range_string,'MeanT_num_observations_'+year_range_string,
                         'MinT_pValue_'+year_range_string, 'MinT_r-squared_'+year_range_string, 'MinT_Slope_'+year_range_string,'MinT_num_observations_'+year_range_string]

    for annual_stats in annual_stats_list:

        file_list = []
        outName_list = []

        temp_list = []
        outDir = os.path.join(root, iata_location_identifier, annual_stats)
        for HV in HV_List:
            inDir = os.path.join(root, HV, 'stats')
            temp_list.append(os.path.join(inDir, "{}_{}.tif".format(HV,annual_stats)))
        file_list.append(temp_list)
        outName_list.append('{}.tif'.format(iata_location_identifier+"_"+annual_stats))

        merge_files(gm, file_list, outDir, outName_list)
    ###################################################################################################
    '''

if __name__ == '__main__':
    #https://stackabuse.com/command-line-arguments-in-python/
    parser = argparse.ArgumentParser()
    #(workpath,HV_List,start_year_inclusive,end_year_inclusive)
    parser.add_argument("--workpath", "-w", help="specify workpath directory")
    parser.add_argument("--hv_tilelist", "-t", help="specify comma delimited ard tile names")
    parser.add_argument("--start_year_inclusive", "-s", help="specify start_year_inclusive")
    parser.add_argument("--end_year_inclusive", "-e", help="specify end_year_inclusive")
    parser.add_argument("--iata_location_identifier", "-i", help="iata_location_identifier")

    # Read arguments from the command line
    args = parser.parse_args()

    

    if args.workpath and args.start_year_inclusive and args.end_year_inclusive and args.hv_tilelist:
        #parse the hv_tilelist here
        hv_tilelist = args.hv_tilelist.split(",")
        print(str(args))
        merge_batch_forHua(args.workpath,hv_tilelist,args.start_year_inclusive,args.end_year_inclusive,args.iata_location_identifier)
        
