# -*- coding: utf-8 -*-
"""
/***************************************************************************
 PyGeoRSDialog
                                 A QGIS plugin
 This plugin automates remote sensing tasks
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2023-09-24
        git sha              : $Format:%H$
        copyright            : (C) 2023 by Dr. Anass MARZOUKI
        email                : anass.marzouki@usmba.ac.ma
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.utils import *
from qgis import *
from PyQt5.QtWidgets import *


# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
import os.path

# Import pushbuttons
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import pyqtSlot
import tarfile
import sys
import os

import itertools
from osgeo import gdal
#import pykml

import numpy as np
import os
import tarfile

from qgis.PyQt import QtWidgets, uic
from qgis.core import (QgsRasterLayer)
from qgis.core import (QgsVectorLayer)

import sys

from PyQt5.QtWidgets import *
#from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog, QTextEdit, QMessageBox, QListWidget, QProgressBar, QPushButton, QRadioButton
from PyQt5.QtGui import QIcon
from PyQt5 import QtWidgets, QtGui, uic, QtCore
from PyQt5.QtGui import QTextCursor
from PyQt5.QtCore import QThread, Qt
from PyQt5.QtCore import QModelIndex

from PyQt5.QtWidgets import QScrollArea, QListWidgetItem
#####
import os

from qgis.PyQt import uic
from qgis.PyQt import QtWidgets
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.utils import *
from qgis import *
from PyQt5.QtWidgets import *


# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
import os.path

# Import pushbuttons
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import pyqtSlot

# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'PyGeoRS_dialog_base.ui'))


class PyGeoRSDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(PyGeoRSDialog, self).__init__(parent)
        # Set up the user interface from Designer through FORM_CLASS.
        # After self.setupUi() you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

        # FILE EXPLORER - WORKING #
        model = QFileSystemModel()
        model.setRootPath('C:/')

        # Create a tree view and set its model to the file system model
        self.treeView.setModel(model)
        self.treeView.setRootIndex(model.index(''))

        # Set the column widths to fit the contents
        self.treeView.header().resizeSection(0, self.treeView.header().sectionSizeHint(0) * 5) # double the size of column 0 (file name)
        self.treeView.header().resizeSection(1, self.treeView.header().sectionSizeHint(1))   # keep the size of column 1 (file size)

        # Create the context menu
        self.context_menu = QMenu(self.treeView)
        show_in_qgis_action = QAction("Show in QGIS", self)
        show_in_qgis_action.triggered.connect(self.show_in_qgis)
        self.context_menu.addAction(show_in_qgis_action)

        #self.context_menu.addAction("Action 2")

        # Connect the customContextMenuRequested signal to a slot function
        self.treeView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.treeView.customContextMenuRequested.connect(self.show_context_menu)

        # Connect the clicked signal of the tree view to the handleClicked function
        self.treeView.clicked.connect(self.handleClicked)


        # Connect the customContextMenuRequested signal to a slot function
    def show_context_menu(self, point):
        # Get the index of the item that was right-clicked
        index = self.treeView.indexAt(point)

        # If the index is valid, show the context menu at the given point
        if index.isValid():
            # Set the current index of the tree view to the clicked item
            self.treeView.setCurrentIndex(index)
            self.context_menu.exec_(self.treeView.mapToGlobal(point))

    def handleClicked(self, index: QModelIndex): #ORIGINAL
        # Get the file path of the clicked file
        model = self.treeView.model()
            # Get the file path of the clicked file
        self.__class__.signal_from_fexplorer = model.filePath(index)

    def show_in_qgis(self):

        from qgis.gui import QgisInterface
        import rasterio
        import numpy as np
        import matplotlib.pyplot as plt
        import os # This is is needed in the pyqgis console also
        # from qgis.core import (QgsRasterLayer)
        # from qgis.core import (QgsVectorLayer)
        from qgis.core import QgsProject


        from qgis.core import QgsRasterLayer
        from PyQt5.QtCore import QFileInfo

        fileInfo = QFileInfo(self.__class__.signal_from_fexplorer)
        path = fileInfo.filePath()
        baseName = fileInfo.baseName()

        layer = QgsRasterLayer(path, baseName)
        QgsProject.instance().addMapLayer(layer)