# -*- coding: utf-8 -*-
"""
/***************************************************************************
 LayerList
                                 A QGIS plugin
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-10-29
        git sha              : $Format:%H$
        copyright            : (C) 2025 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,QFileDialog,QMessageBox 
from qgis.core import QgsProject

# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
from .LayerList_dialog import LayerListDialog
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 LayerList:
    """QGIS Plugin Implementation."""
         
    def select_input_file(self): 
        filename = QFileDialog.getExistingDirectory(selfMT.dlg, "Select output list directory ") 
        selfMT.dlg.inputCombo.clear() 
        selfMT.dlg.inputCombo.insertItem(0,filename)
        selfMT.dlg.inputCombo.setCurrentIndex(0)
        autoPoly = filename+"/LayerList.csv"
        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__) + "\\layerlist\\LayerList.pdf"
        webbrowser.open(MThelp)  
        
    def run(self):
        import tempfile,glob,os
        import random
        import shutil
        import math
        from marinetools.layerlist.LayerList_dialog import LayerListDialog
        global selfMT

        # 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 = LayerListDialog()
            selfMT = self
            self.dlg.inputFileDir.clicked.connect(LayerList.select_input_file) 
            self.dlg.helpButton.clicked.connect(LayerList.help) 
        
        layers = QgsProject.instance().mapLayers().values()
        self.dlg.inputCombo.clear()
        list= (os.path.dirname(layer.source()) for layer in layers)
        noDupList = set(list)
        #self.dlg.inputCombo.addItems(os.path.dirname(layer.source()) for layer in layers)
        self.dlg.inputCombo.addItems(noDupList)

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        outputDir = self.dlg.inputCombo.currentText()

        if result:
            if os.path.exists(outputDir + "/LayerList.csv"):
                os.remove(outputDir + "/LayerList.csv")

            txtFile = open(outputDir + "/LayerList.csv", "w")
            txtFile.write("Layer,Filename,Directory,Projection,EPSG,Format,No_Features,Type,"+
                          "Xmin,Xmax,Ymin,Ymax,MinValue,MaxValue,Rows,Columns,Xres,Yres\n")

            layers = QgsProject.instance().mapLayers().values() # Default output from 
            for layer in layers:
                fullname = layer.source()
                Layer1 = layer.name()
                Filename1 = str(os.path.basename(fullname))
                Directory1 = str(os.path.dirname(fullname))
                #print(layer.name()+" "+str(os.path.basename(fullname)))
                #print(layer.name()+" "+str(os.path.dirname(fullname)))
                crs = layer.crs()
                extent = layer.extent()
            
                # RASTER
                try:
                    infile = QgsRasterLayer(fullname)
                    result = processing.run("gdal:gdalinfo", {'INPUT':fullname,'MIN_MAX':False,'STATS':False,'NOGCP':False,
                                              'NO_METADATA':False,'EXTRA':'','OUTPUT':'TEMPORARY_OUTPUT'})
                    type = "raster"
                except:
                    result = processing.run("gdal:ogrinfo", {'INPUT':fullname,'ALL_LAYERS':False,'SUMMARY_ONLY':True,
                                                    'NO_METADATA':False,'EXTRA':'','OUTPUT':'TEMPORARY_OUTPUT'})
                    type = "vector"

                f= open(result['OUTPUT'])
                oneliner = f.read()
                f.close()
                lines = oneliner.splitlines()
                projCrs = str(oneliner).find("PROJCRS")
                if projCrs == -1:
                    projCrs = str(oneliner).find("GEOGCRS")
                lineplus = oneliner[projCrs+9:projCrs+50]
                endlineplus = lineplus.find('"')
                for line in lines:
                    posDriver = line.find("Driver:")
                    if posDriver != -1:
                        format = line[posDriver+8:]
                    posDriver = line.find("using driver")
                    if posDriver != -1:
                        format = line[posDriver+14:].replace("' successful.","")
                    MinValuePos = line.find("STATISTICS_MINIMUM")
                    if MinValuePos != -1:
                        MinValue = line[MinValuePos+19:]
                    MaxValuePos = line.find("STATISTICS_MAXIMUM")
                    if MaxValuePos != -1:
                        MaxValue = line[MaxValuePos+19:]
                epsgCount = str(crs).find("EPSG")
                EPSGin = str(crs)[epsgCount:].replace(">","")
                #print(type)
                if type == "raster":
                    dict = processing.run("native:rasterlayerproperties", {'INPUT':infile,'BAND':1})
                    Cellsize_X = float(dict['PIXEL_WIDTH'])
                    Cellsize_Y = float(dict['PIXEL_HEIGHT'])

                    xmin = extent.xMinimum()
                    ymin = extent.yMinimum()
                    xmax = extent.xMaximum()
                    ymax = extent.yMaximum()
                    xPixels = infile.width()
                    yPixels = infile.height()
                    Projection1 = lineplus[:endlineplus] # projection name
                    #print(format)
                    #print(lineplus[:endlineplus]) # projection name
                    #print(EPSGin) # EPSG projection number
                    #print(xmin)
                    #print(ymin)
                    #print(xmax)
                    #print(ymax)
                    #print(xPixels)
                    #print(yPixels)
                    #print(Cellsize_X)
                    #print(Cellsize_Y)
                    #print(MinValue)
                    #print(MaxValue)
                    #txtFile.write("Layer,Filename,Directory,Projection,EPSG,Format,No_Features,Type,"+
                    #  "Xmin,Xmax,Ymin,Ymax,MinValue,MaxValue,Rows,Columns,Xres,Yres\n")
                    txtFile.write(Layer1+","+Filename1+","+Directory1+","+Projection1+","+
                                  EPSGin+","+format+", , ,"+
                                  str(xmin)+","+str(xmax)+","+str(ymin)+","+str(ymax)+","+str(MinValue)+","+str(MaxValue)+","+
                                  str(xPixels)+","+str(yPixels)+","+str(Cellsize_X)+","+str(Cellsize_Y)+"\n")
                    
                    
                if type == "vector":
                    for line in lines:
                        vectorTypePos = line.find("Geometry:")
                        if vectorTypePos != -1:
                            vectorType = line[vectorTypePos+10:]
                        featureCountPos = line.find("Feature Count:")
                        if featureCountPos != -1:
                            featureCount = line[featureCountPos+15:]

                    xmin = extent.xMinimum()
                    ymin = extent.yMinimum()
                    xmax = extent.xMaximum()
                    ymax = extent.yMaximum()
                    Projection1 = lineplus[:endlineplus] # projection name
                    #print(format)
                    #print(lineplus[:endlineplus]) # projection name
                    #print(EPSGin) # EPSG projection number
                    #print(xmin)
                    #print(ymin)
                    #print(xmax)
                    #print(ymax)
                    #print(vectorType)
                    #print(featureCount)
                    txtFile.write(Layer1+","+Filename1+","+Directory1+","+Projection1+","+
                                  EPSGin+","+format+","+str(featureCount)+","+vectorType+","+
                                  str(xmin)+","+str(xmax)+","+str(ymin)+","+str(ymax)+", , , , , , \n")
            
                continue

            txtFile.close()
            fname = os.path.dirname(outputDir + "/LayerList.csv")
            vlayer = QgsVectorLayer(outputDir + "/LayerList.csv", "LayerList.csv","ogr")
            QgsProject.instance().addMapLayer(vlayer)
            return
                
