import os, subprocess, time
from threading import Thread
import geopandas as gpd
import rasterio
from shapely.geometry import box

def executeCmd(cmd1,cmd2):
     subprocess.check_call(cmd1, shell=True)
     subprocess.check_call(cmd2, shell=True)

def bbox_intersects_or_within(shapefile_path, geotiff_path):
    # Leer el shapefile
    shapefile = gpd.read_file(shapefile_path)
    # Calcular el bounding box de todas las geometrías del shapefile
    shapefile_bbox = shapefile.total_bounds
    shapefile_bbox_geom = box(*shapefile_bbox)
    
    # Abrir el archivo GeoTIFF
    with rasterio.open(geotiff_path) as src:
        # Calcular el bounding box del GeoTIFF
        geotiff_bbox = src.bounds
        geotiff_bbox_geom = box(*geotiff_bbox)
    
    # Verificar si los bounding boxes intersectan o si uno está dentro del otro
    if shapefile_bbox_geom.intersects(geotiff_bbox_geom) or shapefile_bbox_geom.contains(geotiff_bbox_geom):
        return True
    return False

def mask_cog_with_shapefile(cog_directory, mask_path, output_directory,shapeFile):
  

    counter = 0
    # Procesar cada archivo COG en el directorio
    for cog_file in os.listdir(cog_directory):
        if cog_file.endswith('.tif') or cog_file.endswith('.tiff'):
            cog_path = os.path.join(cog_directory, cog_file)
            output_path = os.path.join(output_directory, cog_file)
            mask_file = os.path.join(mask_path, 'mask_' + cog_file)
            output_path_cog = os.path.join(output_directory, 'COG_' + cog_file)
            counter += 1
            print(counter)
            print(f"Procesando {cog_file}...")

            try:
                cmd1 = f'docker run --rm -v /mnt:/mnt osgeo/gdal gdal_calc.py -A {cog_path} \
                    -B {mask_file} \
                    --outfile={output_path} --calc="A*(B==1)" --NoDataValue=0'
                #subprocess.check_call(cmd, shell=True)

                cmd2 = f'docker run --rm -v /mnt:/mnt osgeo/gdal gdalwarp -r bilinear -co "COMPRESS=DEFLATE" -co "BIGTIFF=YES" -of COG \
                    {output_path} \
                    {output_path_cog}'
                #subprocess.check_call(cmd, shell=True)
                if bbox_intersects_or_within(shapeFile, cog_path):
                    thread = Thread(target=executeCmd, args=(cmd1,cmd2))
                    thread.start() 
                    time.sleep(6)
                else:
                     print(f"COG file is not inside is shape file: {cog_file}")

            except ValueError as ve:
                    print(f"Error procesando {cog_file}: {ve}")

if __name__ == "__main__":
    cog_directory = '/mnt/data/srv/carto_private/08_TEST/norwayMask/input'
    mask_path = '/mnt/data/srv/carto_private/08_TEST/norwayMask/masks'
    output_directory = '/mnt/data/srv/carto_private/08_TEST/norwayMask/output'
    shapeFile = '/mnt/data/srv/carto_private/08_TEST/norwayMask/Noruega-Mask-3857.shp'

    mask_cog_with_shapefile(cog_directory, mask_path, output_directory,shapeFile)

'''
** cut the image with the sahpefile
docker run --rm -v /mnt:/mnt osgeo/gdal gdalwarp -overwrite -r bilinear -tr 2 2 -co "COMPRESS=DEFLATE" -co BIGTIFF=YES -co "PREDICTOR=2" -of COG \
    -cutline /mnt/data/srv/carto_private/08_TEST/norwayMask/Noruega-Mask.shp \
    -crop_to_cutline \
    /mnt/data/srv/carto_private/08_TEST/norwayMask/input/Z8_X150_Y201.tif \
    /mnt/data/srv/carto_private/08_TEST/norwayMask/output/Z8_X150_Y201_crop.tif

docker run --rm -v /mnt:/mnt osgeo/gdal gdal_calc.py -A /mnt/data/srv/carto_private/08_TEST/norwayMask/input/Z8_X150_Y201.tif \
        -B /mnt/data/srv/carto_private/08_TEST/norwayMask/masks/mask_Z8_X150_Y201.tif \
        --outfile=/mnt/data/srv/carto_private/08_TEST/norwayMask/output/Z8_X150_Y201_mask.tif --calc="A*(B==1)" --NoDataValue=0

docker run --rm -v /mnt:/mnt osgeo/gdal gdalwarp -r bilinear -co "COMPRESS=DEFLATE" -co "BIGTIFF=YES" -of COG \
        /mnt/data/srv/carto_private/08_TEST/norwayMask/output/Z8_X150_Y201_mask.tif \
        /mnt/data/srv/carto_private/08_TEST/norwayMask/output/Z8_X150_Y201_mask_COG.tif


        
docker run --rm -v /mnt:/mnt osgeo/gdal gdal_calc.py -A /mnt/data/srv/carto_private/08_TEST/norwayMask/input/Z8_X135_Y179.tif \
        -B /mnt/data/srv/carto_private/08_TEST/norwayMask/masks/mask_Z8_X135_Y179.tif \
        --outfile=/mnt/data/srv/carto_private/08_TEST/norwayMask/output/Z8_X135_Y179_mask.tif --calc="A*(B==1)" --NoDataValue=0

docker run --rm -v /mnt:/mnt osgeo/gdal gdalwarp -r bilinear -co "COMPRESS=DEFLATE" -co "BIGTIFF=YES" -of COG \
        /mnt/data/srv/carto_private/08_TEST/norwayMask/output/Z8_X135_Y179_mask.tif \
        /mnt/data/srv/carto_private/08_TEST/norwayMask/output/Z8_X135_Y179_mask_COG.tif

'''