#region
# -*- coding: utf-8 -*-
"""
/***************************************************************************
 Qalq
                                 A QGIS plugin
 automation tool for building unreal engine heightmaps from terrain data
 Generated by Plugin Builder: http://jonah-sullivan.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2026-05-29
        git sha              : $Format:%H$
        copyright            : (C) 2026 by shark_blood_studios
        email                : zacharydubroc@outlook.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.                                   *
 *                                                                         *
 ***************************************************************************/
"""
#endregion
import os, requests, json
from qgis.PyQt.QtCore import QLocale, QTranslator, QCoreApplication, QSize, QPointF, QRectF
from osgeo import gdal
from qgis.PyQt.QtWidgets import QAction, QFileDialog, QMessageBox
from qgis.PyQt.QtGui import QIcon
from qgis.gui import QgsMapToolEmitPoint, QgsRubberBand
from qgis.PyQt.QtGui import QColor
from qgis.core import (
    QgsRectangle,
    QgsGeometry, 
    Qgis, 
    QgsFeature, 
    QgsProject, 
    QgsRasterLayer, 
    QgsSettings,
    QgsMapSettings,
    QgsVectorLayer, 
    QgsRasterFileWriter, 
    QgsRasterPipe, 
    QgsCoordinateTransform, 
    QgsCoordinateTransformContext,
    QgsCoordinateReferenceSystem,
    QgsMapRendererParallelJob,

)
# Import the code for the dialog
from .qalq_dialog import QalqDialog
import os.path
from urllib.parse import parse_qs, unquote

#######
####selection tool
######
#region
class ExtentSet(QgsMapToolEmitPoint):

    def __init__(self, canvas, grid_resolution, iface):
        super().__init__(canvas)
        self.canvas = canvas
        self.size = grid_resolution
        self.isDrawing = True
        self.user_selection = None
        self.rubberBand = QgsRubberBand(canvas, Qgis.GeometryType.Polygon)
        self.rubberBand.setColor(QColor(255, 0, 0, 127))
        self.rubberBand.setWidth(2)
        self.isDrawing = True
        self.iface = iface

    def _updateSquarePreview(self, center):
        half_size = self.size / 2.0
        rect = QgsRectangle(
            center.x() - half_size,
            center.y() - half_size,
            center.x() + half_size,
            center.y() + half_size,
        )
        self.rubberBand.setToGeometry(QgsGeometry.fromRect(rect), None)

    def canvasPressEvent(self, e):
        self.isDrawing = True
        self.currentCenter = self.toMapCoordinates(e.pos())
        self._updateSquarePreview(self.currentCenter)

        center = self.toMapCoordinates(e.pos())
        half_size = self.size / 2.0
        rect = QgsRectangle(
            center.x() - half_size,
            center.y() - half_size,
            center.x() + half_size,
            center.y() + half_size,
        )
        # send execution back to plugin
        self.iface.crop_extent(rect)

    def canvasMoveEvent(self, e):
        if self.isDrawing:
            self.currentCenter = self.toMapCoordinates(e.pos())
            self._updateSquarePreview(self.currentCenter)
        else:
            return

    def canvasReleaseEvent(self, e):
        self.isDrawing = False
        self.canvas.unsetMapTool(self)

    def deactivate(self):
        self.rubberBand.reset()
        super().deactivate()
######
####end
####selection tool
######
#endregion

class Qalc:
#gen from plugin_template
#region
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface

        self.canvas = self.iface.mapCanvas()

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QgsSettings().value('locale/userLocale', QLocale().name())[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            '{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Qalc')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str

        :returns: Translated version of message.
        :rtype: str
        """
        return QCoreApplication.translate('Qalq', message)


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)
        self.actions.append(action)
        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = os.path.join(os.path.dirname(__file__), 'icon.png')
        self.add_action(
            icon_path,
            text=self.tr(u'Qalc'),
            callback=self.run,
            parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Qalc'),
                action)
            self.iface.removeToolBarIcon(action)
#endregion
    def run(self):
        """Run method that performs all the real work"""
        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = QalqDialog()
            self.dlg.mQgsFileWidget.setStorageMode(self.dlg.mQgsFileWidget.GetDirectory)
            self.dlg.mResolutionComboBox.addItems(['256','505','1024'])
            self.dlg.mDPIComboBox.addItems(['150','300','600'])
            self.dlg.mResolutionComboBox.setCurrentText("505")
            self.dlg.mDPIComboBox.setCurrentText("300")
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec()
        # See if OK was pressed
        if result:
            #globals set here
            self.height_layer = self.dlg.mMapLayerComboBox.currentLayer()
            self.albedo_layer = self.dlg.mAlbedoLayerComboBox.currentLayer()
            self.cropped_layer = None
            self.selected_directory = self.dlg.mQgsFileWidget.filePath()
            self.grid_resolution = int(self.dlg.mResolutionComboBox.currentText())
            self.DPI = int(self.dlg.mResolutionComboBox.currentText())
            self.start()

    def start(self):
        height_layer = self.height_layer 
        albedo_layer = self.albedo_layer 
        grid_resolution = self.grid_resolution
        selected_directory = self.selected_directory 
        height_provider = height_layer.dataProvider().name().lower()
        albedo_provider = albedo_layer.dataProvider().name().lower()
        is_raster = isinstance(height_layer, QgsRasterLayer)
        invalid_providers = {"wms", "wmts", "xyz", "arcgismapserver", "wfs", "wcs"}
        if not height_layer:
            QMessageBox.warning(self.iface.mainWindow(), "dang!", "no layer seleceted!")
            return
        if not selected_directory:
            QMessageBox.warning(self.iface.mainWindow(), "dang!", "no output path selected!")
            return
        if height_provider in invalid_providers:
            QMessageBox.warning(self.iface.mainWindow(), "dang!", "invalid height layer!")
            return
        if albedo_provider not in invalid_providers:
            QMessageBox.warning(self.iface.mainWindow(), "dang!", "invalid albedo layer!")
            return
        if not is_raster:
            QMessageBox.warning(self.iface.mainWindow(), "dang!", "invalid height layer!")
            return
        try:
            self.tool = ExtentSet(self.canvas, grid_resolution, self)
            self.canvas.setMapTool(self.tool)
        except Exception as e:
            self.iface.messageBar().pushMessage(
                "dang", f"an error occurred: {str(e)}", 
            )

    def crop_extent(self, aoi_extent):
        height_input_layer = self.height_layer
        albedo_input_layer = self.albedo_layer
        grid_res = self.grid_resolution
        if not height_input_layer:
            QMessageBox.warning(self.iface.mainWindow(), "dang", "No active layer found.")
            return

        height_input_path = height_input_layer.dataProvider().dataSourceUri().split('|')[0]
        
        proj_win = [
            aoi_extent.xMinimum(),
            aoi_extent.yMaximum(),
            aoi_extent.xMaximum(),
            aoi_extent.yMinimum()
        ]
        output_path = f"/vsimem/{height_input_layer}_heightmap.tif"
        translate_opts = gdal.TranslateOptions(
            projWin=proj_win,
            width=grid_res,
            height=grid_res,
            resampleAlg=gdal.GRIORA_Bilinear,
            creationOptions=['COMPRESS=NONE','BIGTIFF=IF_NEEDED']
        )
        try:
            ds = gdal.Translate(output_path, height_input_path, options=translate_opts)
            if ds is not None:
                ds.FlushCache()
                cropped_layer = QgsRasterLayer(output_path, "heightmap")
                if cropped_layer.isValid():
                    QgsProject.instance().addMapLayer(cropped_layer)
                    gtif = gdal.Open(output_path)
                    elevation_band = gtif.GetRasterBand(1)
                    stats = elevation_band.GetStatistics(True, True)
                    min_elev = stats[0]
                    max_elev = stats[1]
                    self.cropped_layer = cropped_layer
                    
                    elev_range = max_elev - min_elev
                    z_scale = (elev_range/512.0) * 100

                    

                    ### export calls once extent is set
                    ###

                    self.height_export(min_elev, max_elev, output_path)
                    self.albedo_export(aoi_extent, albedo_input_layer,z_scale, min_elev, max_elev, elev_range, grid_res)

                    #
                    #todo:
                    #   how to get road spline/building .shp files 
                    #   exported out at same scale for either blender or unreal
                    ###
                    ### + scale_values idk a better way to call yet


                else:
                    QMessageBox.critical(
                        self.iface.mainWindow(), 
                        "dang!", 
                        "Failed to load the cropped raster. make sure you have the proper one selected"
                    )
                ds=None
            else:
                raise Exception("dang, gdal.Translate : None")
        except Exception as e:
            QMessageBox.critical(self.iface.mainWindow(), "dang", f"main GDAL clip failed: {str(e)}")


    def height_export(self, min_elev, max_elev, src_path):
        #in-memory raster clip -> 16bit grayscale png
        final_path = os.path.join(self.selected_directory, "heightmap.png")
        translate_opts = gdal.TranslateOptions(
            format='PNG',
            outputType=gdal.GDT_UInt16,
            scaleParams=[[min_elev, max_elev, 0, 65535]]
        )
        try:
            ds = gdal.Translate(final_path, src_path, options=translate_opts)
            if ds is not None:
                ds.FlushCache()
        except Exception as e:
            QMessageBox.critical(self.iface.mainWindow(), "dang", f"height export failed: {str(e)}")

    def albedo_export(self, aoi_extent, albedo_layer, z_scale, min_elev, max_elev, elev_range, grid_res):
        #basemap clip -> albedo.png, for texture in ue material
        final_path = os.path.join(self.selected_directory, "albedo.png")
        grid_res = self.grid_resolution
        dpi = self.DPI
        image_location = final_path
        settings = QgsMapSettings()
        settings.setLayers([albedo_layer])
        settings.setBackgroundColor(QColor(255, 255, 255))
        settings.setOutputSize(QSize(grid_res, grid_res))
        settings.setExtent(aoi_extent)
        settings.setOutputDpi(dpi)
        settings.setDestinationCrs(self.height_layer.crs()) 
        render = QgsMapRendererParallelJob(settings)
        def finished():
            img = render.renderedImage()
            img.save(image_location, "png")
            self.export_finished(z_scale, min_elev, max_elev, elev_range, grid_res)
        render.finished.connect(finished)
        render.start()

    def export_finished(self, z_scale, min_elev, max_elev, elev_range, grid_res):
        # x-y-z scaling on import
        # need to add map scaling on albedo texture but I think thats
        # same as res
        copystr = f"X=100.0,Y=100.0,Z={z_scale:.6f}"
        QMessageBox.information(
            self.iface.mainWindow(),
            "Export Finished",
            f"<b>UE Landscape Scaling:</b><br>"
            f"{copystr}<br><br>"
            f"<b>Min Elevation:</b> {min_elev:.2f} m<br>"
            f"<b>Max Elevation:</b> {max_elev:.2f} m<br>"
            f"<b>Range:</b> {elev_range:.2f} m<br>"
        )

