import json, os, sys, argparse
from subprocess import Popen, PIPE
try:
    from osgeo import ogr, osr, gdal
except:
    sys.exit('ERROR: cannot find GDAL/OGR modules')

def search_files(directory='.', extension='tif', resolution='MV_'):
    images=[]
    extension = extension.lower()
    resolution = resolution.lower()
    for dirpath, dirnames, files in os.walk(directory):
        for name in files:
            if dirpath.upper().find("_PROD") >= 0 or dirpath.upper().find("_TMP") >= 0 :
                continue
            if extension and name.lower().endswith(extension) and name.lower().find(resolution) >= 0 :
                upname = name.upper()
                
                if upname != name :
                    upabspath = os.path.abspath(os.path.join(dirpath, upname))
                    abspath = os.path.abspath(os.path.join(dirpath, name))
                    os.rename(abspath, upabspath)
                    name = upname
                #print(os.path.join(dirpath, name))
                abspath = os.path.abspath(os.path.join(dirpath, name))
                images.append(abspath)

    return images

def reprojectRaster(absfile):
    temp_file = absfile + ".old"
    os.rename(absfile, temp_file)
    
    
    p = Popen(['gdalwarp', '-t_srs', 'EPSG:4326', temp_file, absfile], stdout=PIPE)
#    p.wait()
    output = p.communicate()[0]
    if p.returncode != 0: 
        print("gdalwarp failed %d : %s" % (p.returncode, output))
        with open("gdalwrap_log.err",'a') as err:
            err.write("######################################################################################################")
            err.write(absfile)
            err.write(output)
            err.write("######################################################################################################")
            os.remove(absfile)
            os.rename(temp_file, absfile)
        return 1
        
    print("gdalwarp succeeded on : "+absfile)
    os.remove(temp_file)
    return 0

if __name__ == "__main__":
    # Make parser object
    parser = argparse.ArgumentParser(description=
        """
        Reproj tif image's file in  WGS84
        """)
    

    #####################################################
    driver = gdal.GetDriverByName('GTiff')
    driver.Register()
    ##############################################
    parser.add_argument('-colldir', action='store', required=True, help='Directory containing collection data')
    
    parser.add_argument('-overwrite', choices=['no', 'all',"json","png"],  default='no', required=False, help='[Optional] Overwrite already existing files, default no')
    
    args=parser.parse_args()
    
    mvtifs=[]
    mvtifs=search_files(args.colldir)

    for file in mvtifs:
        print("################################################################")
        print("Processing file " + file)
        absfile = os.path.abspath(file)
        raster = gdal.Open(absfile)
        
        proj = osr.SpatialReference(wkt=raster.GetProjection())
        mv_epsg = int(proj.GetAttrValue('AUTHORITY',1))
        
        if mv_epsg != 4326 :
             print("Reprojection needed. Launching gdalwrap.")
             raster = None
             projerr = reprojectRaster(absfile)
             if projerr:
                 continue
            


