# -*- coding: utf-8 -*-
"""
/***************************************************************************
 SpikeRemoval
                                 A QGIS plugin
 Removes Spurious pixels from bathymetry data that can look like trees
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-03-18
        git sha              : $Format:%H$
        copyright            : (C) 2025 by Dr Tim Le Bas
        email                : tlb@noc.ac.uk
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/
"""
import sys
import traceback
import os, glob
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction,QFileDialog 
from qgis.core import QgsProject 

# Import the code for the dialog
from .SpikeRemoval_dialog import SpikeRemovalDialog
import os.path
from qgis.core import Qgis,QgsMessageLog
from qgis.gui import QgsMessageBar

from qgis.core import QgsProcessing
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterRasterLayer
from qgis.core import QgsProcessingParameterRasterDestination
from qgis.core import QgsProcessingParameterDefinition
from qgis.core import QgsVectorLayer
from qgis.core import (QgsSymbol,QgsSimpleFillSymbolLayer,QgsRendererCategory,QgsCategorizedSymbolRenderer)
from qgis.core import QgsRasterLayer
from qgis.core import QgsRasterBandStats
from qgis.core import QgsSingleBandGrayRenderer,QgsContrastEnhancement

import processing



class LoadingScreenDlg:
    """Loading screen animation."""
    from qgis.PyQt.QtWidgets import QDialog, QLabel 
    from qgis.PyQt.QtGui import QMovie, QPalette, QColor

    def __init__(self, gif_path):
        self.dlg = self.QDialog()
        self.dlg.setWindowTitle("Please Wait")
        #self.dlg.setWindowModality(False)
        self.dlg.setFixedSize(200, 100)
        pal = self.QPalette()
        #role = self.QPalette.Background
        #pal.setColor(role, self.QColor(255, 255, 255))
        self.dlg.setPalette(pal)
        self.label_animation = self.QLabel(self.dlg)
        self.movie = self.QMovie(gif_path)
        self.label_animation.setMovie(self.movie)

    def start_animation(self):
        self.movie.start()
        self.dlg.show()
        return

    def stop_animation(self):
        self.movie.stop()
        self.dlg.done(0)     

class SpikeRemoval:
    """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
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'SpikeRemoval_{}.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'&Tree Removal')

        # 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

    # noinspection PyMethodMayBeStatic
    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, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('SpikeRemoval', 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 = ':/plugins/SpikeRemoval/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Tree Removal'),
            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'&Tree Removal'),
                action)
            self.iface.removeToolBarIcon(action)
    def select_input_file1(self): 
        filename, _filter = QFileDialog.getOpenFileName(selfMT.dlg, "Select input bathymetry file ","", '*.img *.tif*') 
        # Add layer to frame, find last in list, add to end of list, create all new lists
        selfMT.dlg.lineCombo1.clear() 
        selfMT.dlg.lineCombo1.insertItem(0,filename)
        selfMT.dlg.lineCombo1.setCurrentIndex(0)
        #autofill
        radius = selfMT.dlg.Radius.text()
        if radius == "":
            radius = "3"
        threshold = selfMT.dlg.Threshold.text()
        if threshold == "":
            threshold = "0.5"
        autoPoly = filename[:-4]+"_despiked_"+radius+"_"+threshold+".img"
        selfMT.dlg.lineEdit_2.setText(autoPoly)
        if os.path.exists(autoPoly):
            selfMT.dlg.exists2.setText("Existing file will be overwritten")
        else:
            selfMT.dlg.exists2.setText("")
    def select_input_file2(self): 
        filename, _filter = QFileDialog.getSaveFileName(selfMT.dlg, "Select output interpolated file ","", '*.img') 
        selfMT.dlg.lineEdit_2.setText(filename) 
        if os.path.exists(filename):
            selfMT.dlg.exists1.setText("Existing file will be overwritten")
        else:
            selfMT.dlg.exists1.setText("")
    def indexChanged(self): 
        selectedLayerIndex = selfMT.dlg.lineCombo1.currentIndex()
        currentText = selfMT.dlg.lineCombo1.currentText()
        layers = QgsProject.instance().mapLayers().values()
        a=0
        filename="NULL"
        for layer in (layer1 for layer1 in layers if str(layer1.type())== "1" or str(layer1.type())== "LayerType.Raster"):
            if a == selectedLayerIndex:
                filename = str(layer.source())
            a=a+1
        filename1= selfMT.dlg.lineEdit_2.text()[0:len(currentText[:-4])]
        #if filename1[0:3] == "_tr" or currentText[:-4] == filename1[0:len(currentText[:-4])]:
        if filename1[0:3] == "_tr":
            filename = currentText
        #autofill
        radius = selfMT.dlg.Radius.text()
        if radius == "":
            radius = "3"
        threshold = selfMT.dlg.Threshold.text()
        if threshold == "":
            threshold = "0.5"
        txt_threshold = threshold.replace(".","")
        autoPoly = filename[:-4]+"_despiked_"+radius+"_"+txt_threshold+".img"
        selfMT.dlg.lineEdit_2.setText(autoPoly)
        if os.path.exists(autoPoly):
            selfMT.dlg.exists2.setText("Existing file will be overwritten")
        else:
            selfMT.dlg.exists2.setText("")

    def help(self): 
        import webbrowser
        import marinetools
        MThelp = os.path.dirname(marinetools.__file__) + "\\SpikeRemoval\\SpikeRemoval.pdf"
        webbrowser.open(MThelp)  

    def run(self):
        import random
        import marinetools
        from marinetools.SpikeRemoval.SpikeRemoval_dialog import SpikeRemovalDialog
        global selfMT
        """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 = SpikeRemovalDialog()
            selfMT = self
            self.dlg.pushButton_1.clicked.connect(SpikeRemoval.select_input_file1) 
            self.dlg.pushButton_2.clicked.connect(SpikeRemoval.select_input_file2) 
            self.dlg.lineCombo1.currentIndexChanged.connect(SpikeRemoval.indexChanged)
            self.dlg.Radius.textChanged.connect(SpikeRemoval.indexChanged) 
            self.dlg.Threshold.textChanged.connect(SpikeRemoval.indexChanged) 
            self.dlg.helpButton.clicked.connect(SpikeRemoval.help) 
            
        # Fetch the currently loaded layers
        layers = QgsProject.instance().layerTreeRoot().children() 
        layers = QgsProject.instance().mapLayers().values()
        # Clear the contents of the comboBox from previous runs
        # self.dlg = MBES_SegmentationDialog()
        self.dlg.lineCombo1.clear() 
        # Populate the comboBox with names of all the loaded layer   
        self.dlg.lineCombo1.addItems([layer.name() for layer in layers if str(layer.type())== "1" or str(layer.type())== "LayerType.Raster"])
        SpikeRemoval.indexChanged(self) 
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec()
        
        # See if OK was pressed
        if result:
            import glob
            selectedLayerIndex = self.dlg.lineCombo1.currentIndex()
            currentText = selfMT.dlg.lineCombo1.currentText()
            layers = QgsProject.instance().mapLayers().values()
            a=0
            filename="NULL"
            for layer in (layer1 for layer1 in layers if str(layer1.type())== "1" or str(layer1.type())== "LayerType.Raster"):
                if a == selectedLayerIndex:
                    filename = str(layer.source())
                a=a+1
            if currentText not in filename:
                filename = currentText
            filename1 = filename
            
            # Test input file to find if supported 
            from marinetools.fileTest import fileTest
            #filename1 = fileTest.main(filename1,"raster")
            #if filename1[0:5] == "Error":
            #    print(filename1)
            #    return
            
            filename2 = self.dlg.lineEdit_2.text()  
  
            radius = self.dlg.Radius.text()
            threshold = self.dlg.Threshold.text()
            if radius == "":
                radius = "3"
            if threshold == "":
                threshold = "0.5"
            txt_threshold = threshold.replace(".","")
            filename3 = filename[:-4]+"_despiked_slope_"+radius+"_"+txt_threshold+".img"
            radius = str(int(float(radius)*2.0)+1)
            newdir = str(os.path.dirname(filename1) + "/tempMT")
            if not os.path.exists(newdir):
                os.mkdir(newdir)

            plugin_dir = os.path.dirname(__file__)
            gif_path = os.path.join(plugin_dir, "loading.gif")
            self.loading_screen = LoadingScreenDlg(gif_path)  # init loading dlg
            self.loading_screen.start_animation()  # start loading dlg
            

            import string
            rand = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))

            medianFilt = newdir + "/medianFilt"+rand+".img"
            
            
            result = processing.run("grass:r.neighbors", {'input':filename1,'selection':None,
                                                 'method':1,'size':radius,'gauss':None,
                                                 'quantile':'','-c':True,'-a':False,
                                                 'weight':'','output':medianFilt,
                                                          'GRASS_REGION_PARAMETER':None,'GRASS_REGION_CELLSIZE_PARAMETER':0,'GRASS_RASTER_FORMAT_OPT':'','GRASS_RASTER_FORMAT_META':''})
            
            #medianFilt = result['output']


            tempName1 = os.path.split(filename1)[1]
            name = tempName1.split('.')[0]
            layerRef1 = name + '@1'
            tempName2 = os.path.split(medianFilt)[1]
            name = tempName2.split('.')[0]
            layerRef2 = name + '@1'
            expr = '"'+ layerRef1 + '" - "' + layerRef2 + '"'
            minusRaster = newdir + "/minusRaster"+rand+".img"
            infile = QgsRasterLayer(filename1)
            crs = infile.crs()
            extent = infile.extent()

            #result = processing.run("qgis:rastercalculator", {'EXPRESSION':expr,'LAYERS':[filename1,medianFilt],
            #                                          'CELLSIZE':None,'EXTENT':None,'CRS':None,'OUTPUT':minusRaster})
            result = processing.run("native:rastercalc", {'EXPRESSION':expr,'LAYERS':[filename1,medianFilt],
                                                     'CELL_SIZE':None,'EXTENT':None,'CRS':crs,'OUTPUT':minusRaster})
            processing.run("gdal:assignprojection", {'INPUT':minusRaster,'CRS':crs})
            #minusRaster = result['OUTPUT']
            tempName3 = os.path.split(minusRaster)[1]
            name = tempName3.split('.')[0]
            layerRef3 = name + '@1'
            #  ' IF ( "layerRef3" < threshold and "layerRef3" > -threshold, layerRef1, layerRef2)'
            expression = ' IF ("'+layerRef3+'" < '+ threshold + ' and "' + layerRef3 + '" > -' + threshold + \
                         ', "' + layerRef1 + '", "' + layerRef2 + '")'
            result = processing.run("native:rastercalc", {'LAYERS':[minusRaster,filename1,medianFilt],'EXPRESSION':expression,
                                                 'EXTENT':extent,'CELL_SIZE':None,'CRS':crs,'OUTPUT':filename2})
            processing.run("native:slope", {'INPUT':filename2,'Z_FACTOR':1,'OUTPUT':filename3})

            self.loading_screen.stop_animation()

            fname = os.path.dirname(str(filename3))
            vlayer = QgsRasterLayer(str(filename3), str(filename3[len(fname)+1:-4]))
            QgsProject.instance().addMapLayer(vlayer)
            
            renderer=vlayer.renderer()
            provider=vlayer.dataProvider()
            GrayRenderer = QgsSingleBandGrayRenderer(provider,1) #create a new renderer
            myType = renderer.dataType(1)
            myEnhancement = QgsContrastEnhancement(myType)
            contrast_enhancement = QgsContrastEnhancement.StretchToMinimumMaximum
            myEnhancement.setContrastEnhancementAlgorithm(contrast_enhancement,True)
            myEnhancement.setMinimumValue(0)   #Set the minimum 0
            vlayerStats = vlayer.dataProvider().bandStatistics(1,QgsRasterBandStats.All)
            vlayerMax = vlayerStats.maximumValue
            myEnhancement.setMaximumValue(vlayerMax)
            vlayer.setRenderer(GrayRenderer)
            vlayer.renderer().setContrastEnhancement(myEnhancement)
            vlayer.renderer().setGradient(QgsSingleBandGrayRenderer.WhiteToBlack) # WhiteToBlack
            vlayer.triggerRepaint()

            fname = os.path.dirname(str(filename2))
            vlayer = QgsRasterLayer(str(filename2), str(filename2[len(fname)+1:-4]))
            QgsProject.instance().addMapLayer(vlayer)
            
            
            pass
