# -*- coding: utf-8 -*-

"""
/***************************************************************************
 LandCoverDownloader
                                 A QGIS plugin
 Downloads Sentinel-2 Land Cover Data from Esri's Living Atlas
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2026-01-11
        copyright            : (C) 2026 by CustomCartographix
        email                : john@customcartographix.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

 /***************************************************************************
 *                                                                         *
 *   This script contains the necessary functions for the land cover       *
 *   downloader processing algorithm to work.                              *
 *                                                                         *
 ***************************************************************************/
"""

# Import necessary modules
from PyQt5.QtCore import QUrl
from PyQt5.QtNetwork import QNetworkRequest
from qgis._core import QgsNetworkAccessManager
from qgis import processing


def downloadLandCoverRaster(i, utm_zones, year, scratch_folder):
    """
    Function to download land cover data based on current location

    Returns filename of saved land cover raster
    """

    # Download data based on whichever UTM zone the aoi is within
    # Get UTM zone and create output filename
    zone = utm_zones[i]
    zone_id = str(zone[0]) + zone[1]
    output_filename = scratch_folder + '/' + zone_id + ".tif"

    # Get date range for URL
    if year == "2024":
        date_range = "20240101-20241231"
    else:
        year_int = int(year)
        next_year = year_int + 1
        date_range = year + "0101-" + str(next_year) + "0101"

    # Download data from Living Atlas and write to scratch folder
    url = ("https://lulctimeseries.blob.core.windows.net/lulctimeseriesv003/lc" + year + "/" + zone_id +
           "_" + date_range + ".tif")
    qurl = QUrl(url)
    request = QNetworkRequest(qurl)
    network_access_manager = QgsNetworkAccessManager()
    response = network_access_manager.blockingGet(request)
    content = response.content()
    open(output_filename, "wb").write(content)
    temp_lc = open(output_filename, )
    temp_lc.close()

    # Return filename of downloaded land cover raster
    return output_filename


def mosaicAndClipRasters(input_lc_filenames, aoi_layer, scratch_folder, output_lc_raster):
    """
    Function to mosaic and clip land cover rasters based on input AOI.

    Writes output to processing algorithm output (i.e. temp file or file destination)
    """

    # Clip/mosaic lc data
    # Slightly different methodology if greater than one tile (i.e. need to mosaic after clipping)
    if len(input_lc_filenames) == 1:
        input_lc = input_lc_filenames[0]
        processing.run("gdal:cliprasterbymasklayer", {'INPUT': input_lc, 'MASK': aoi_layer,
                                                      'SOURCE_CRS': None, 'TARGET_CRS': aoi_layer.crs().authid(),
                                                      'TARGET_EXTENT': None,
                                                      'NODATA': None, 'ALPHA_BAND': False,
                                                      'CROP_TO_CUTLINE': True, 'KEEP_RESOLUTION': False,
                                                      'SET_RESOLUTION': False, 'X_RESOLUTION': None,
                                                      'Y_RESOLUTION': None, 'MULTITHREADING': False,
                                                      'OPTIONS': '', 'DATA_TYPE': 0, 'EXTRA': '',
                                                      'OUTPUT': output_lc_raster})
    else:
        clipped_rasters = []
        for i in range(len(input_lc_filenames)):
            temp_name = scratch_folder + '/clipped_lc_' + str(i) + '.tif'
            clipped_rasters.append(temp_name)
            processing.run("gdal:cliprasterbymasklayer",
                           {'INPUT': input_lc_filenames[i], 'MASK': aoi_layer,
                            'SOURCE_CRS': None, 'TARGET_CRS': aoi_layer.crs().authid(),
                            'TARGET_EXTENT': None,
                            'NODATA': None, 'ALPHA_BAND': False,
                            'CROP_TO_CUTLINE': True, 'KEEP_RESOLUTION': False,
                            'SET_RESOLUTION': False, 'X_RESOLUTION': None,
                            'Y_RESOLUTION': None, 'MULTITHREADING': False,
                            'OPTIONS': '', 'DATA_TYPE': 0, 'EXTRA': '',
                            'OUTPUT': temp_name})
        processing.run("gdal:merge", {'INPUT': clipped_rasters,
                                      'PCT': False, 'SEPARATE': False, 'NODATA_INPUT': None, 'NODATA_OUTPUT': None,
                                      'OPTIONS': '', 'EXTRA': '', 'DATA_TYPE': 0,
                                      'OUTPUT': output_lc_raster})
