# -*- coding: utf-8 -*-
"""
/***************************************************************************
 RasterCoverage
                                 A QGIS plugin
 Makes polygon of area of raster data
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2023-09-04
        git sha              : $Format:%H$
        copyright            : (C) 2023 by 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.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.PyQt.QtWidgets import QAction,QFileDialog 
from qgis.core import QgsProject 

# Initialize Qt resources from file resources.py
# Import the code for the dialog
from .RasterCoverage_dialog import RasterCoverageDialog
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
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 RasterCoverage:
    """QGIS Plugin Implementation."""

    def select_input_file1(self): 
        filename, _filter = QFileDialog.getOpenFileName(selfMT.dlg, "Select input bathymetry file ","", '*.img *.tif') 
        selfMT.dlg.comboBox.clear() 
        selfMT.dlg.comboBox.insertItem(0,filename)
        selfMT.dlg.comboBox.setCurrentIndex(0)
        autoPoly = filename[:-4]+"_coverage.shp"
        selfMT.dlg.lineEdit_4.setText(autoPoly)
        if os.path.exists(autoPoly):
            selfMT.dlg.exists1.setText("Existing file will be overwritten")
        else:
            selfMT.dlg.exists1.setText("")

    def select_input_file4(self): 
        filename, _filter = QFileDialog.getSaveFileName(selfMT.dlg, "Select output contours shapefile","", '*.shp') 
        selfMT.dlg.lineEdit_4.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.comboBox.currentIndex()
        currentText = selfMT.dlg.comboBox.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_4.text()[0:len(currentText[:-4])]
        #if filename1[0:3] == "_co" or currentText[:-4] == filename1[0:len(currentText[:-4])]:
        if filename1[0:3] == "_co":
            filename = currentText
        #autofill
        autoPoly = filename[:-4]+"_coverage.shp"
        selfMT.dlg.lineEdit_4.setText(autoPoly)
        if os.path.exists(autoPoly):
            selfMT.dlg.exists1.setText("Existing file will be overwritten")
        else:
            selfMT.dlg.exists1.setText("")

    def help(self): 
        import webbrowser
        import marinetools
        MThelp = os.path.dirname(marinetools.__file__) + "\\rastercoverage\\RasterCoverage.pdf"
        webbrowser.open(MThelp)  
        
    def run(self):
        import random
        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 = RasterCoverageDialog()
            selfMT = self
            self.dlg.pushButton_1.clicked.connect(RasterCoverage.select_input_file1) 
            self.dlg.pushButton_4.clicked.connect(RasterCoverage.select_input_file4) 
            self.dlg.helpButton.clicked.connect(RasterCoverage.help) 
            self.dlg.comboBox.currentIndexChanged.connect(RasterCoverage.indexChanged)
           
        # Fetch the currently loaded layers
        layers = QgsProject.instance().mapLayers().values()
        self.dlg.comboBox.clear() 
        # Populate the comboBox with names of all the raster loaded layers  (type="1")
        self.dlg.comboBox.addItems([layer.name() for layer in layers if str(layer.type())== "1" or str(layer.type())== "LayerType.Raster"])
        RasterCoverage.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.comboBox.currentIndex()
            currentText = selfMT.dlg.comboBox.currentText()
            layers = QgsProject.instance().mapLayers().values()
            a=0
            filename="NULL"
            for layer in (layer1 for layer1 in layers if str(layer1.type())== "1"):
                if a == selectedLayerIndex:
                    filename = str(layer.source())
                a=a+1
            if currentText not in filename:
                filename = currentText

            filename1 = filename 
            filename4 = self.dlg.lineEdit_4.text()  

            if os.path.exists(filename4):
                os.remove(filename4)
            print("Input file = "+str(filename1))
                  
            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
            
            #take the file and make it usable by raster calculator
            tempName = os.path.split(filename1)[1]
            if tempName.count('.') > 1:
                name = tempName[:-4]
            else:
                name = tempName.split('.')[0]
            layerRef = name + '@1'
            # change to 0.0 and 1.0
            
            expr = '"'+ layerRef + '" * 0.0 + 1.0'
            infile = QgsRasterLayer(filename1)
            crs = infile.crs()
            extent = infile.extent()
            print("Expression = "+str(expr))

            result = processing.run("native:rastercalc", {'LAYERS':filename1,'EXPRESSION':expr,'EXTENT':extent,
                                                 'CELL_SIZE':None,'CRS':crs,'OUTPUT':'TEMPORARY_OUTPUT'})
            polyCov = result['OUTPUT']
            result = processing.run("gdal:polygonize", {'INPUT':polyCov,'BAND':1,'FIELD':'DN',
                                                        'EIGHT_CONNECTEDNESS':False,'EXTRA':'',
                                                        'OUTPUT':'TEMPORARY_OUTPUT'})
            delHole = result['OUTPUT']
            result = processing.run("native:deleteholes", {'INPUT':delHole,'MIN_AREA':0,'OUTPUT':filename4})
            
            self.loading_screen.stop_animation()
            
            fname = os.path.dirname(str(filename4))
            vlayer = QgsVectorLayer(str(filename4), str(filename4[len(fname)+1:-4]), "ogr")
            QgsProject.instance().addMapLayer(vlayer)
            
            pass

