# -*- coding: utf-8 -*-
"""
/***************************************************************************
 PyGeoRS
                                 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.                                   *
 *                                                                         *
 ***************************************************************************/
"""
import pkg_resources
import subprocess
import os
import os.path
import tempfile
from PyQt5.QtWidgets import QProgressDialog, QMessageBox
from PyQt5.QtCore import Qt
import time


def package_installed(pkg_name):
    """Check if a Python package is installed without importing it."""
    try:
        pkg_resources.get_distribution(pkg_name)
        return True
    except pkg_resources.DistributionNotFound:
        return False


def read_config():
    # Determine the full path to config.txt based on the current script's location
    config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.txt')

    # Read the content of config.txt
    with open(config_path, 'r') as f:
        return f.read().strip() == 'True'


def update_config(status=True):
    config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.txt')
    with open(config_path, 'w') as f:
        f.write(str(status))


def install_package(pkg_name):
    current_directory = os.path.dirname(os.path.abspath(__file__))

    # For the 'unmixing' package, since it has its own setup process
    if pkg_name == "unmixing":
        setup_directory = os.path.join(current_directory, 'unmixing-master')
        command = f"pip install -e {setup_directory}"
    else:
        command = f"pip install {pkg_name}"

    osgeo_root = os.environ.get('OSGEO4W_ROOT')
    if not osgeo_root:
        print("OSGeo4W root not found!")
        return

    with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.bat', prefix='install_package_') as f:
        f.write("@echo off\n")
        f.write(f"call \"{osgeo_root}\\bin\\o4w_env.bat\"\n")
        f.write(f"python -m {command}\n")
        temp_path = f.name

    subprocess.run(temp_path, shell=True)
    os.remove(temp_path)


def install_packages():
    progress = QProgressDialog("Initializing...", None, 0, 100)
    progress.setWindowTitle("PyGeoRS v0.1")
    progress.setWindowModality(Qt.WindowModal)
    progress.setFixedSize(300, 120)

    packages_to_install = ["rasterio", "earthpy", "unmixing", "scikit-learn"]
    packages_to_check = ["rasterio", "earthpy", "unmixing", "sklearn"]

    packages_installed_in_session = False

    for i, pkg in enumerate(packages_to_install):
        if not package_installed(packages_to_check[i]):
            progress.forceShow()
            progress.setLabelText(f"Installing {pkg}...")
            install_package(pkg)
            packages_installed_in_session = True
        progress.setValue((i + 1) * 100 / len(packages_to_install))

    progress.setValue(100)
    progress.close()

    return packages_installed_in_session


if not read_config():
    if not all(package_installed(pkg) for pkg in ["rasterio", "earthpy", "unmixing", "sklearn"]):
        packages_installed_in_this_session = install_packages()
        update_config(True)

        if packages_installed_in_this_session:
            msg_box = QMessageBox()
            msg_box.setIcon(QMessageBox.Information)
            msg_box.setText("Installation completed. Please restart QGIS to ensure all changes take effect.")
            msg_box.setWindowTitle("PyGeoRS v0.1")
            msg_box.exec_()



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
from .PyGeoRS_dialog import PyGeoRSDialog
import os.path

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

import itertools
from osgeo import gdal
#import pykml

import rasterio
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
import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QSplashScreen, QApplication

class PyGeoRS:
    """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',
            'PyGeoRS_{}.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'&PyGeoRS')

        # 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('PyGeoRS', 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/PyGeoRS/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'PyGeoRS'),
            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'&PyGeoRS'),action)
            self.iface.removeToolBarIcon(action)
            print('PyGeoRS Unloaded')

    def reload(self):
        for action in self.actions:
            self.iface.addPluginToMenu(self.tr(u'&PyGeoRS'),action)
            self.iface.addToolBarIcon(action)
            print('PyGeoRS reloaded')

    def run(self):
        """Run method that performs all the real work"""
        app = QApplication.instance()
        code_dir = os.path.dirname(os.path.abspath(__file__))
        splash_pix = QPixmap(os.path.join(code_dir, 'splash.png'))
        self.splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
        self.splash.show()

        # Use a timer to delay the initialization and showing of your main dialog
        QTimer.singleShot(1500, self.initialize_and_show_dialog)



    def initialize_and_show_dialog(self):

    # 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
        self.splash.close()
        if self.first_start == True:
            self.first_start = False       

            self.dlg = PyGeoRSDialog()

            self.pygeors_functions = RSFunctions(self.dlg) #Instance
            #Declare Pushbuttons & CheckBoxes
            self.pygeors_functions.disable_all_tasks()
            self.pygeors_functions.welcome_msg()

            #self.dlg.pB_load_mtl.hide() #launch GUI with hidden "Load MTL file button"
            self.dlg.pB_load_shapefile.hide()

            self.dlg.pB_quit.clicked.connect(self.pygeors_functions.close_main_window) #Close main window
            self.dlg.pB_load_shapefile.clicked.connect(self.pygeors_functions.load_shapefile) #Close main window
            self.dlg.pB_load_mtl.clicked.connect(self.pygeors_functions.load_mtl) 
            self.dlg.pB_select_output_folder.clicked.connect(self.pygeors_functions.select_output_folder)
            self.dlg.pB_help.clicked.connect(self.pygeors_functions.show_help) #load dlg

            self.dlg.cB_dn_to_toa.stateChanged.connect(self.pygeors_functions.dn_to_toa_cb_changed)


            #self.dlg.cB_generate_fcc.clicked.connect(self.pygeors_functions.set_fcc)
            #self.dlg.cB_calculate_br.clicked.connect(self.pygeors_functions.calculate_band_ratio)
            #self.dlg.cB_calculate_index.clicked.connect(self.pygeors_functions.save_index_image)

            self.dlg.textEdit = self.dlg.findChild(QTextEdit, "textEdit")
            self.dlg.pB_load_data.clicked.connect(self.pygeors_functions.load_landsat_data)
            self.dlg.pB_proceed.clicked.connect(self.pygeors_functions.set_folder_and_proceed)
            #self.dlg.pB_load_mtl.clicked.connect(self.load_mtl)
            #self.dlg.pB_help.clicked.connect(self.show_help)

                    #ComboBox for FCC
            self.dlg.comboBox.activated[str].connect(self.pygeors_functions.red_fcc_activated) #RED Fcc
            self.dlg.comboBox_2.activated[str].connect(self.pygeors_functions.green_fcc_activated) #GREEN Fcc
            self.dlg.comboBox_3.activated[str].connect(self.pygeors_functions.blue_fcc_activated) #BLUE Fcc

            #Combo for index
            self.dlg.comboBox_4.activated[str].connect(self.pygeors_functions.index_activated)

            # #ComboBox for BR : Red = a/b; Green = c/d; Blue = e/f
            self.dlg.comboBox_6.activated[str].connect(self.pygeors_functions.a_br_activated) #RED BR --> a
            self.dlg.comboBox_7.activated[str].connect(self.pygeors_functions.b_br_activated) #RED BR --> b

            self.dlg.comboBox_8.activated[str].connect(self.pygeors_functions.c_br_activated) #GREEN BR --> c
            self.dlg.comboBox_9.activated[str].connect(self.pygeors_functions.d_br_activated) #GREEN BR --> d

            self.dlg.comboBox_10.activated[str].connect(self.pygeors_functions.e_br_activated) #BLUE BR --> e
            self.dlg.comboBox_11.activated[str].connect(self.pygeors_functions.f_br_activated) #BLUE BR --> f

            #ComboBox for Indices:
            self.dlg.comboBox_4.activated[str].connect(self.pygeors_functions.index_activated)

            #Radio buttons YES / NO to toggle shapefile load
            self.dlg.radioButton = self.dlg.findChild(QRadioButton)
            #self.pushButton = self.findChild(QPushButton, "pushButton")
            #self.pushButton.setEnabled(True) #Load shapefile button
            #self.radioButton.toggled.connect(self.enablePushButton)

            self.dlg.radioButton.toggled.connect(lambda: self.pygeors_functions.enablePushButton(self.dlg.radioButton, self.dlg.radioButton_2))
            self.dlg.radioButton_2.toggled.connect(lambda: self.pygeors_functions.enablePushButton(self.dlg.radioButton, self.dlg.radioButton_2))

        #self.dlg.cB_generate_fcc.setEnabled(False)


    # show the dialog
        self.dlg.show()
    # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            pass
            # Do something useful here - delete the line containing pass and
    
           # substitute with your code.





