#
# This file is part of INPE/ENANDES Project - Processing Module.
# Copyright (C) 2024 INPE.
#
# enandes-processing is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
import logging
import os

# Configure the logging system
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def getGeoT(extent, nlines, ncols):
    '''
    This function computes the resolution based on data dimensions.
    '''
    resx = (extent[2] - extent[0]) / ncols
    resy = (extent[3] - extent[1]) / nlines
    return [extent[0], resx, 0, extent[3] , 0, -resy]

def geo2grid(x, y, geoT):
    '''
    This function returns the grid point associated to a spatial location.
    - param x The spatial x-coordiante.
    - param y The spatial y-coordiante.
    - param geoTransform A list of 6 coefficients describing an affine transformation to georeference a grid.
    - return The grid point line and column.
    '''
    lin = (y - geoT[3]) / geoT[5]
    col = (x - geoT[0]) / geoT[1]
    return int(lin), int(col)

def grid2geo(lin, col, geoT):
    '''
    This function returns the spatial location of a grid point.
    - param geoTransform A list of 6 coefficients describing an affine transformation to georeference a grid.
    - param col The grid point column.
    - param row The grid point row.
    - return The spatial location.
    '''
    x = col * geoT[1] + geoT[0]
    y = lin * geoT[5] + geoT[3]
    return x, y

def getExtent(gt, shape):
    '''
    This function returns the extent based on the given GDAL
    geo-transform parameters and dimensions.
    '''
    llx = gt[0]
    lly = gt[3] + ((shape[0]) * gt[5])
    urx = gt[0] + ((shape[1])  * gt[1])
    ury = gt[3]
    return (llx, lly, urx, ury)

def createWorldFile(path, extent, nlines, ncols):
    # More info: https://en.wikipedia.org/wiki/World_file
    geoT = getGeoT(extent, nlines, ncols)
    with open(path, 'w') as file:
        for i in [1, 2, 4, 5, 0, 3]: # order of 6 coefficients in World File (e.g. *.pgw).
            file.write('{}\n'.format(geoT[i]))

# Create directory
def create_directory_if_not_exists(directory):
    """ It Create the directory if it does not exist."""
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
            return True  # Directory created
        else:
            return False  # Directory already exists

        logger.info(f"Directory created or already exists: {directory}")

    except OSError as error:
        logger.error(f"Error creating directory {directory}: {error}")
        return False 

