# -*- coding: utf-8 -*-
"""
/***************************************************************************
 FeatureIterator
                                 A QGIS plugin
 Iterate over a vector layer s features
                              -------------------
        begin                : 2017-01-27
        git sha              : $Format:%H$
        copyright            : (C) 2017-23 by Centro de Informação Geoespacial do Exército
        email                : igeoe@igeoe.pt
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 __future__ import absolute_import
from builtins import str
from builtins import object
from qgis.PyQt.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, Qt
from qgis.PyQt.QtWidgets import QAction, QMessageBox, QComboBox, QToolBar
from qgis.PyQt.QtGui import QIcon
from qgis.gui import QgsMessageBar

# Initialize Qt resources from file resources.py
from . import resources

# Import the code for the DockWidget
from .feature_iterator_dockwidget import FeatureIteratorDockWidget
import os.path
from qgis.core import *


class FeatureIterator(object):
    """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',
            'FeatureIterator_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Feature Iterator')
        
        cigeoeToolBarExists = False
        for x in iface.mainWindow().findChildren(QToolBar): 
            if x.windowTitle() == 'CIGeoE':
                self.toolbar = x
                cigeoeToolBarExists = True
        if cigeoeToolBarExists==False:
            self.toolbar = self.iface.addToolBar(u'CIGeoE')
		
        self.toolbar.setObjectName(u'FeatureIterator')

        #print "** INITIALIZING FeatureIterator"

        self.pluginIsActive = False
        self.dockwidget = None


        # my instance variables
        self.itIndex = 0
        self.undoFeat = []
        self.undoFeatIndex = []
        self.undoLayerName = NULL
        self.layers = []
        self.memorizedSelectedFeatures = []

    # 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('FeatureIterator', 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:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToVectorMenu(
                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/FeatureIterator/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Iterate over a vector layer\'s features'),
            callback=self.run,
            parent=self.iface.mainWindow())

        ############################################################# JUNTAR AQUI ICONES PARA TOOLBAR, SE QUISER!!!
        #icon_path = ':/plugins/FeatureIterator/btnBack.png'
        #self.add_action(
        #    icon_path,
        #    text=self.tr(u'Select previous feature'),
        #    callback=self.prevFeature,
        #    parent=self.iface.mainWindow())
        #icon_path = ':/plugins/FeatureIterator/btnForward.png'
        #self.add_action(
        #    icon_path,
        #    text=self.tr(u'Select next feature'),
        #    callback=self.nextFeature,
        #    parent=self.iface.mainWindow())
        #icon_path = ':/plugins/FeatureIterator/btnRemove.png'
        #self.add_action(
        #    icon_path,
        #    text=self.tr(u'Remove feature'),
        #    callback=self.removeFeature,
        #    parent=self.iface.mainWindow())

    #--------------------------------------------------------------------------

    def onClosePlugin(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""

        #print "** CLOSING FeatureIterator"

        # disconnects
        self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)

        # remove this statement if dockwidget is to remain
        # for reuse if plugin is reopened
        # Commented next statement since it causes QGIS crashe
        # when closing the docked window:
        # self.dockwidget = None

        self.pluginIsActive = False


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""

        #print "** UNLOAD FeatureIterator"

        for action in self.actions:
            self.iface.removePluginVectorMenu(
                self.tr(u'&Feature Iterator'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    #--------------------------------------------------------------------------

    def run(self):
        """Run method that loads and starts the plugin"""

        if not self.pluginIsActive:
            self.pluginIsActive = True

            #print "** STARTING FeatureIterator"

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = FeatureIteratorDockWidget()
				
				#listeners - must be here, to not fire twice when clicked
                self.dockwidget.btnNext.clicked.connect(self.nextFeature)
                self.dockwidget.btnPrev.clicked.connect(self.prevFeature)
                self.dockwidget.btnRemove.clicked.connect(self.removeFeature) 
                self.dockwidget.btnRefresh.clicked.connect(self.refreshLayers)
                self.dockwidget.btnUndo.clicked.connect(self.undoRemoveFeature)
                self.dockwidget.comboBox.currentIndexChanged.connect(self.newLayerSelected)
                self.dockwidget.btnMemSelection.clicked.connect(self.memSelectedFeatures)
                self.dockwidget.fieldComboBox.currentIndexChanged.connect(self.newFieldSelected)
                self.dockwidget.valueComboBox.currentIndexChanged.connect(self.newValueSelected)

                self.dockwidget.attributeValueRadioButton.toggled.connect(self.attributeValueRadioButton_active)
                self.dockwidget.selectedFeaturesRadioButton.toggled.connect(self.selectedFeaturesRadioButton_active)
                #setup initial values
                self.loadLayersIntoComboBox()

                self.dockwidget.attributeValueRadioButton.setChecked(True)
                self.dockwidget.selectedFeaturesRadioButton.setChecked(False)

                self.resetMyVariables()

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # show the dockwidget
            # TODO: fix to allow choice of dock location
            self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)

            self.dockwidget.show()
        else:
            self.iface.removeDockWidget(self.dockwidget)
            self.onClosePlugin()

    def attributeValueRadioButton_active(self, on):
        if on:
            self.dockwidget.attributeValueRadioButton.setChecked(True)
            self.dockwidget.selectedFeaturesRadioButton.setChecked(False)
            self.dockwidget.fieldComboBox.setEnabled(True)
            self.dockwidget.valueComboBox.setEnabled(True)
            self.dockwidget.btnMemSelection.setEnabled(False)
        return

    def selectedFeaturesRadioButton_active(self, on):
        if on:
            self.dockwidget.attributeValueRadioButton.setChecked(False)
            self.dockwidget.selectedFeaturesRadioButton.setChecked(True)
            self.dockwidget.fieldComboBox.setEnabled(False)
            self.dockwidget.valueComboBox.setEnabled(False)
            self.dockwidget.btnMemSelection.setEnabled(True)
            self.memorizedSelectedFeatures=[]
        return



    def newLayerSelected(self):
        global itIndex
        itIndex=-1
        self.loadFieldsIntoComboBox()
        self.resetMyVariables()
        # QMessageBox.information(None, "Teste:", str(itIndex))
        return

    def newFieldSelected(self):
        # add field distinct values to values combo box
        selectedLayerIndex = self.dockwidget.comboBox.currentIndex()
        selectedLayer = self.layers[selectedLayerIndex]
        values_list=[]
        field = self.dockwidget.fieldComboBox.currentText()
        if(field!="All"):
            idx = selectedLayer.dataProvider().fieldNameIndex(field)
            values = selectedLayer.uniqueValues(idx)
            for value in values:
                values_list.append(str(value))
        self.dockwidget.valueComboBox.clear()
        self.dockwidget.valueComboBox.addItems(values_list)
        self.resetMyVariables()
        return

    def newValueSelected(self):
        self.resetMyVariables()
        return

    def resetMyVariables(self):
        # on new layer selected, reset "my" variables
        # clear removed features stack
        self.undoFeat=[]
        # clear removed features index stack
        self.undoFeatIndex=[]
        # clear removed features layer
        self.undoLayerName=NULL
        # reset index counter
        self.itIndex=0

    def loadLayersIntoComboBox(self):
        layers = list(QgsProject.instance().mapLayers().values())
        self.layers = []
        layers_list=[]
        for layer in layers:
            if layer.type()==QgsMapLayer.VectorLayer:
                layers_list.append(layer.name())
                self.layers.append(layer)
        self.dockwidget.comboBox.clear()
        self.dockwidget.comboBox.addItems(layers_list)
        #reset attribute combo
        self.loadFieldsIntoComboBox()

    def loadFieldsIntoComboBox(self):
        # add layer fields to fields combo box
        selectedLayerIndex = self.dockwidget.comboBox.currentIndex()
        try:
            selectedLayer = self.layers[selectedLayerIndex]
        except IndexError:
            return
        fields_list=[]
        fields_list.append("All")
        prov = selectedLayer.dataProvider()
        fields = prov.fields()
        for field in fields:
            fields_list.append(field.name())
        self.dockwidget.fieldComboBox.clear()
        self.dockwidget.fieldComboBox.addItems(fields_list)
        # as first option is "All", value combobox can simply be cleared out
        self.dockwidget.valueComboBox.clear()

    def getCurrentQueryExpression(self):
        field = self.dockwidget.fieldComboBox.currentText()
        value = self.dockwidget.valueComboBox.currentText()
        if(field=="All" or value=="" ):
            return NULL
        else:
            if(value=="NULL"):
                return QgsExpression( u"\""+field+"\" is NULL" )
            else:
                return QgsExpression( u"\""+field+"\" = '"+value+"'" )

    def getCurrentFeatureFromIndex(self, layer):
        iter=[]
        expr = self.getCurrentQueryExpression()
        if(expr==NULL):
            iter = layer.getFeatures()
        else:
            iter=layer.getFeatures( QgsFeatureRequest(expr) )
        # alternative to check memorized selected features
        if self.dockwidget.selectedFeaturesRadioButton.isChecked():
            iter=self.memorizedSelectedFeatures

        featList=[]
        for feat in iter:
            featList.append( feat )
        newlist = sorted(featList, key=lambda x: x.id())
        counter=0
        for feat in newlist:
            if counter == self.itIndex:
                return feat
            counter+=1	
        return NULL

    def getFeatureCountOfGivenQueriedLayer(self, layer):
        expr = self.getCurrentQueryExpression()
        if(expr==NULL):
            iter = layer.getFeatures()
        else:
            iter=layer.getFeatures( QgsFeatureRequest(expr) )

        # alternative to check memorized selected features
        if self.dockwidget.selectedFeaturesRadioButton.isChecked():
            iter=self.memorizedSelectedFeatures

        counter=0
        for feat in iter:
            counter+=1
        return counter
		
    def centerMapInFeature(self):
        selectedLayerIndex = self.dockwidget.comboBox.currentIndex()
        selectedLayer = self.layers[selectedLayerIndex]
        if (selectedLayer == NULL):
            return 
        if (self.getFeatureCountOfGivenQueriedLayer(selectedLayer) == 0):
            self.iface.mapCanvas().refresh()
            return
        megaFeat = self.getCurrentFeatureFromIndex(selectedLayer)
        canvas = self.iface.mapCanvas()
        layerList=[]
        layerList.append(megaFeat.id())
        selectedLayer.selectByIds(layerList)
        self.iface.mapCanvas().panToSelected(selectedLayer)
        if self.dockwidget.fitFeatureExtentCheckBox.isChecked():
            self.iface.mapCanvas().zoomToSelected(selectedLayer)
        self.iface.mapCanvas().refresh()
        return

    def nextFeature(self):
        if not self.pluginIsActive:
            self.run()
            return
        selectedLayerIndex = self.dockwidget.comboBox.currentIndex()
        if(selectedLayerIndex<0):
            return
        selectedLayer = self.layers[selectedLayerIndex]
        if (selectedLayer == NULL):
            return 
        if(self.getFeatureCountOfGivenQueriedLayer(selectedLayer)==0):
            return
        self.itIndex+=1
        if self.itIndex >= self.getFeatureCountOfGivenQueriedLayer(selectedLayer):
            self.itIndex=0
        self.centerMapInFeature()
        return 

    def prevFeature(self):
        if not self.pluginIsActive:
            self.run()
            return
        selectedLayerIndex = self.dockwidget.comboBox.currentIndex()
        if(selectedLayerIndex<0):
            return
        selectedLayer = self.layers[selectedLayerIndex]
        if (selectedLayer == NULL):
            return  
        if(self.getFeatureCountOfGivenQueriedLayer(selectedLayer)==0):
            return
        self.itIndex-=1
        if self.itIndex < 0:
            self.itIndex=self.getFeatureCountOfGivenQueriedLayer(selectedLayer)-1
        self.centerMapInFeature()
        return 

    def removeFeature(self):
        if not self.pluginIsActive:
            self.run()
            return
        selectedLayerIndex = self.dockwidget.comboBox.currentIndex()
        if(selectedLayerIndex<0):
            return
        selectedLayer = self.layers[selectedLayerIndex]
        if (selectedLayer == NULL):
             return  
        if(self.getFeatureCountOfGivenQueriedLayer(selectedLayer)==0):
            return
        megaFeat=self.getCurrentFeatureFromIndex(selectedLayer)
        if not selectedLayer.isEditable():
            selectedLayer.startEditing()
        selectedLayer.deleteFeature(megaFeat.id())
        # alternative to remove memorized selected feature
        if self.dockwidget.selectedFeaturesRadioButton.isChecked():
            for obj in self.memorizedSelectedFeatures:
                if obj.id() == megaFeat.id():
                    self.memorizedSelectedFeatures.remove(obj)
                    break
        #selectedLayer.commitChanges()
        self.undoFeat.append(megaFeat)
        self.undoFeatIndex.append(self.itIndex)
        self.undoLayerName=selectedLayer.name()
        if self.itIndex >= self.getFeatureCountOfGivenQueriedLayer(selectedLayer):
            self.itIndex=0
        self.centerMapInFeature()
        return 

    def undoRemoveFeature(self):
        if not self.pluginIsActive:
            self.run()
            return
        if len(self.undoFeat)==0:
            return
        selectedLayerIndex = self.dockwidget.comboBox.currentIndex()
        if(selectedLayerIndex<0):
            return
        selectedLayer = self.layers[selectedLayerIndex]
        if (selectedLayer == NULL):
            return
        # does a check if the deleted feature was from the current selected layer
        # if yes, then puts the deleted layer there
        if selectedLayer.name() != self.undoLayerName:
            return
        if not selectedLayer.isEditable():
            selectedLayer.startEditing()
        featToUndo=self.undoFeat.pop()
        selectedLayer.addFeature(featToUndo)
		# alternative to undo memorized selected feature
        if self.dockwidget.selectedFeaturesRadioButton.isChecked():
            self.memorizedSelectedFeatures.append(featToUndo)
        #selectedLayer.commitChanges()
        self.itIndex=self.undoFeatIndex.pop()

        if(len(self.undoFeat)==0):
            self.undoLayerName=NULL
        self.centerMapInFeature()
        return

    def refreshLayers(self):
        if not self.pluginIsActive:
            self.run()
            return
        self.loadLayersIntoComboBox()
        self.resetMyVariables()
        return

    def memSelectedFeatures(self):
        selectedLayerIndex = self.dockwidget.comboBox.currentIndex()
        if(selectedLayerIndex<0):
            QMessageBox.information(self.iface.mainWindow(), "Error", 'No layer selected.')
            return
        selectedLayer = self.layers[selectedLayerIndex]
        if len(selectedLayer.selectedFeatures())==0:
            QMessageBox.information(self.iface.mainWindow(), "Error", 'No features selected.')
            return
        self.memorizedSelectedFeatures = selectedLayer.selectedFeatures()
        self.iface.messageBar().pushMessage("Info", "Memorized "+(str(len(self.memorizedSelectedFeatures)))+" features from layer "+selectedLayer.name()+".", Qgis.Info, 3)
        return