import trends_calculation
import argparse
import os
import utility_functions
import gdal
import glob

import shutil
import time


def trend_stats_generic(inputdir,outputdir,regex_match):
    file_path_list = glob.glob(inputdir + os.sep +"*"+regex_match +"*.tif")
    print('file list: ', file_path_list[0])
    (data_annual, data_slope, data_rvalue, data_pvalue, t_res, dim, trans, prj, data_numobservations) = trends_calculation.get_stats_for_3d_raster_stack_from_file_list(file_path_list)
    print('Exporting!')
    if not os.path.exists(outputdir):
        os.mkdir(outputdir)
    t_res, y_res, x_res = data_annual.shape
    dim = [x_res, y_res, 1]
    utility_functions.saveGeoTiff(
        os.path.join(outputdir, regex_match + 'Slope.tif'),
        data_slope, dim, trans, prj, dtype=gdal.GDT_Float32)
    utility_functions.saveGeoTiff(
        os.path.join(outputdir, regex_match + 'pValue.tif'),
        data_pvalue, dim, trans, prj, dtype=gdal.GDT_Float32)
    utility_functions.saveGeoTiff(
        os.path.join(outputdir, regex_match + 'r-squared.tif'),
        data_rvalue ** 2, dim, trans, prj, dtype=gdal.GDT_Float32)





if __name__ == '__main__':

    #input_folder = r"C:\Users\rhussain\Desktop\pycharm_project_data\urban-heat-islands\atlanta_m2m\standalone_test\MaxSeason2Input"
    #output_folder = r"C:\Users\rhussain\Desktop\pycharm_project_data\urban-heat-islands\atlanta_m2m\standalone_test\MaxSeason2Output"
    

    #INTENSITY annual comes from uhi_intensity
    #INTENSITY_STACK comes from uhi_stats_intensity_stack

    #input_folder = r"\\igskmncnfs016.cr.usgs.gov\lsrdfs1\UHI\data\PreHPCTesting\INTENSITY_ANNUAL\MAXLST"
    #output_folder = r"\\igskmncnfs016.cr.usgs.gov\lsrdfs1\UHI\data\PreHPCTesting\INTENSITY_STACK"

    parser = argparse.ArgumentParser()
    parser.add_argument("--input_folder", "-w", help="specify input_folder")
    parser.add_argument("--output_folder", "-t", help="specify output_folder")
    args = parser.parse_args()

    #input_folder = "/caldera/projects/usgs/eros/urban_heat_islands/Phase1/FSD/output_folder/INTENSITY_ANNUAL"
    #output_folder = "/caldera/projects/usgs/eros/urban_heat_islands/Phase1/FSD/output_folder/INTENSITY_STACK"


    output_folder = args.output_folder
    if os.path.exists(output_folder):
        shutil.rmtree(output_folder)
        time.sleep(5)
    if not os.path.exists(output_folder):
        os.mkdir(output_folder)

    trend_stats_generic(args.input_folder,args.output_folder,"MEANLST")
    trend_stats_generic(args.input_folder,args.output_folder,"MAXLST")