# -*- coding: utf-8 -*-
"""
/***************************************************************************
 LucasDownloadManager
                                 A QGIS plugin
 This plugin provides possibility to download selected LUCAS points.
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2020-12-05
        git sha              : $Format:%H$
        copyright            : (C) 2020 by Jaroslav Zeman, CTU Prague
        email                : jaros.zeman@gmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 os.path
import csv
import sys
import json
import logging
import time
import platform
from tempfile import mkstemp
from pathlib import Path

from osgeo import gdal
gdal.UseExceptions()

from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt, pyqtSignal
from qgis.PyQt.QtGui import QIcon, QPixmap
from qgis.PyQt.QtWidgets import QAction, QProgressBar, QFileDialog
# Initialize Qt resources from file resources.py
from .resources import *

from qgis.core import Qgis, QgsTask, QgsApplication, QgsVectorLayer, QgsProject, QgsMapLayerProxyModel, QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsMessageLog
from qgis.utils import iface
from qgis.gui import QgsFileWidget, QgsMapCanvas

# Import the code for the DockWidget
from .lucas_download_manager_dockwidget import LucasDownloadManagerDockWidget

# Import st_lucas
sys.path.insert(0, os.path.dirname(__file__))
from st_lucas import LucasRequest, LucasIO, LucasClassAggregate, LucasClassTranslate, check_owslib
from st_lucas.exceptions import LucasLoadError, LucasDataError, LucasRequestError, LucasDownloadError, LucasOWSLibError
from st_lucas.logger import Logger

# Import owslib
from owslib.fes import PropertyIsEqualTo, Or

import requests
from urllib.request import urlopen

import webbrowser

class QGisLogHandler(logging.Handler):
    """Custom logging class that bounces messages to the QGIS.
    """
    def __init__(self):
        super(QGisLogHandler, self).__init__()

    def emit(self, record):
        """ Write the log message.

        :param record: record to emit
        """
        if not record.msg:
            return

        if record.levelno >= logging.ERROR:
            QgsMessageLog.logMessage(
                record.msg, 'ST_LUCAS', level=Qgis.Critical
            )
        elif record.levelno >= logging.WARNING:
            QgsMessageLog.logMessage(
                record.msg, 'ST_LUCAS', level=Qgis.Warning
            )
        elif record.levelno >= logging.INFO or record.levelno >= logging.DEBUG:
            # QGIS has no debug level
            QgsMessageLog.logMessage(
                record.msg, 'ST_LUCAS', level=Qgis.Info)

class LucasDownloadManager:
    """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
        self.task_manager = QgsApplication.taskManager()

        # 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',
            'LucasDownloadManager_{}.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'&ST_LUCAS Download Manager')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'LucasDownloadManager')
        self.toolbar.setObjectName(u'LucasDownloadManager')

        #print "** INITIALIZING LucasDownloadManager"

        self.pluginIsActive = False
        self.dockwidget = None

        self.groups = {}

        # set logging
        if len(Logger.handlers) == 0:
            handler = QGisLogHandler()
            handler.setFormatter(logging.Formatter("%(message)s"))
            Logger.addHandler(handler)

    # 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('LucasDownloadManager', 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.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/lucas_download_manager/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Download LUCAS points'),
            callback=self.run,
            parent=self.iface.mainWindow())

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

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

        # print "** CLOSING LucasDownloadManager"

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


        self.dockwidget.year06.setChecked(False)
        self.dockwidget.year09.setChecked(False)
        self.dockwidget.year12.setChecked(False)
        self.dockwidget.year15.setChecked(False)
        self.dockwidget.year18.setChecked(True)
        self.dockwidget.yearAll.setChecked(False)
        # Commented in ui
        # self.dockwidget.nomenclature.setChecked(False)
        # self.dockwidget.nomenclature1.setChecked(False)
        self.dockwidget.stAggregation.setChecked(False)
        self.dockwidget.stAggregation.setEnabled(False)
        self.dockwidget.all.setChecked(True)
        self.dockwidget.countryNames.deselectAllOptions()
        self.dockwidget.outputDir.setFilePath('')
        self.dockwidget.jsonPath.setFilePath('')
        self.dockwidget.groupContent.clear()
        self.dockwidget.groupNames.clear()
        self.groups = {}
        self.dockwidget.labelLC.clear()
        self.dockwidget.labelID.clear()
        self.dockwidget.labelYear.clear()
        self.dockwidget.labelPhoto.clear()
        self.dockwidget.tabWidget.setCurrentIndex(0)

        # 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 LucasDownloadManager"

        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&LUCAS Download Manager'),
                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 LucasDownloadManager"

            # 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 = LucasDownloadManagerDockWidget()


                # Output directory initialization
                self.dockwidget.outputDir.setDialogTitle("Save file")
                # self.dockwidget.outputDir.setFilter("GeoPackage (*.gpkg);;Geography Markup Language (*.gml)")
                self.dockwidget.outputDir.setFilter("GeoPackage (*.gpkg)")
                self.dockwidget.outputDir.setStorageMode(QgsFileWidget.SaveFile)


                self.dockwidget.download.clicked.connect(self.onDownload)


                # Radio buttons
                self.dockwidget.countryNames.setEnabled(False)
                self.dockwidget.activeLayers.setEnabled(False)
                self.dockwidget.activeLayers.setFilters(QgsMapLayerProxyModel.PolygonLayer)
                self.dockwidget.curCanvas.clicked.connect(self.check)
                self.dockwidget.country.clicked.connect(self.check)
                self.dockwidget.vectorLayers.clicked.connect(self.check)


                # Load data from csv into combobox
                self._countries_list = self.loadCountries(os.path.join(os.path.dirname(__file__), "countries_codes.csv"))
                self.dockwidget.country.clicked.connect(self.fillComboBox)


                # LC1 class aggregation
                self.dockwidget.jsonPath.setDialogTitle("Define groups")
                self.dockwidget.jsonPath.setFilter("JSON (*.json)")
                self.dockwidget.jsonPath.setStorageMode(QgsFileWidget.GetFile)
                self.dockwidget.jsonPath.fileChanged.connect(self.loadGroups)
                self.dockwidget.groupNames.itemClicked.connect(self.onItemClick)
                self.dockwidget.groupsApply.clicked.connect(self.onGroupsApply)
                
                # Nomenclature translation
                self.dockwidget.csvPath.setFilter("CSV (*.csv)")
                self.dockwidget.csvPath.setStorageMode(QgsFileWidget.GetFile)
                self.dockwidget.csvPath.fileChanged.connect(self.fillColumnComboBox)
                self.dockwidget.translationApply.clicked.connect(self.onTranslationApply)
                
                # Photos
                self.dockwidget.refreshButton.clicked.connect(self.showPhotoInPlugin)
                self.dockwidget.clearPhotoButton.clicked.connect(self.clearPhoto)
                self.dockwidget.webPhotoButton.clicked.connect(self.showPhotoInBrowser)
                self.dockwidget.comboBoxPhoto.currentIndexChanged.connect(self.showPhotoInPlugin)
                self.dockwidget.pushButtonBack.setEnabled(False)
                self.dockwidget.pushButtonNext.setEnabled(False)
                self.dockwidget.refreshButton.clicked.connect(self.setBackNextButtons)
                self.dockwidget.comboBoxPhoto.currentIndexChanged.connect(self.setBackNextButtons)
                self.dockwidget.pushButtonNext.clicked.connect(self.onPushButtonNext)
                self.dockwidget.pushButtonBack.clicked.connect(self.onPushButtonBack)
                self.dockwidget.savePhotoButton.clicked.connect(self.downloadPhotos)
                
                # Years
                self.dockwidget.yearAll.stateChanged.connect(self.setCheckedYears)
                
                # Space-time aggregation
                self.dockwidget.year06.stateChanged.connect(self.setSpaceTimeAgg)
                self.dockwidget.year09.stateChanged.connect(self.setSpaceTimeAgg)
                self.dockwidget.year12.stateChanged.connect(self.setSpaceTimeAgg)
                self.dockwidget.year15.stateChanged.connect(self.setSpaceTimeAgg)
                self.dockwidget.year18.stateChanged.connect(self.setSpaceTimeAgg)
                self.dockwidget.yearAll.stateChanged.connect(self.setSpaceTimeAgg)
                self.dockwidget.stAggregation.setEnabled(False)

            # 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.RightDockWidgetArea, self.dockwidget)
            self.dockwidget.show()

    def _isLucasLayer(self, path, checkST=False):
        ds = gdal.OpenEx(path, gdal.OF_VECTOR)
        metadata = ds.GetMetadata()
        data = metadata['LUCAS_ST'] == '1' if checkST else 'LUCAS_CLIENT_VERSION' in metadata.keys()
        ds.Close()

        return data

    def isLayerValid(self):
        """Check selected layer."""
        nlayers = len(iface.layerTreeView().selectedLayers())
        if nlayers == 0:
            iface.messageBar().pushMessage('No layer selected', duration=5, level=Qgis.Warning)
            return False

        if nlayers > 1:
            iface.messageBar().pushMessage('Only one layer must be selected', duration=5, level=Qgis.Warning)
            return False

        layer = iface.layerTreeView().selectedLayers()[0]
        gpkg_path = layer.dataProvider().dataSourceUri().split("|")[0]
        if self._isLucasLayer(gpkg_path) is False:
            iface.messageBar().pushMessage('Not valid LUCAS layer', duration=5, level=Qgis.Warning)
            return False

        return True

    def getLayerPath(self):
        """Get layer path."""
        layer = iface.layerTreeView().selectedLayers()[0]
        layer_path = layer.dataProvider().dataSourceUri().split("|")[0]

        return (layer_path, layer)

    def onGroupsApply(self):
        """Create new columns in which are aggregated LC1 classes stored."""
        if self.isLayerValid():
            layer_path, layer = self.getLayerPath()
            try:
                aggregation = LucasClassAggregate(
                    layer_path,
                    mappings_file=self.dockwidget.jsonPath.filePath()
                )
                aggregation.apply()
                layer = QgsVectorLayer(layer_path, "aggregated", "ogr")
                exform = QgsCoordinateTransform(layer.crs(),
                                                iface.mapCanvas().mapSettings().destinationCrs(),
                                                QgsProject.instance())
                iface.mapCanvas().setExtent(exform.transform(layer.extent()))
                iface.mapCanvas().refreshAllLayers()
                self.iface.messageBar().pushMessage("Aggregation was successfully applied!", duration=5, level=Qgis.Success)
            except LucasLoadError as e:
                self.iface.messageBar().pushMessage("Error", f"{e}", duration=5, level=Qgis.Critical)


    def onItemClick(self, item):
        """On click display content of selected group."""

        classes = self.groups[item.text()]
        if len(classes) > 1:
            self.dockwidget.groupContent.setText(', '.join(classes))
        elif len(classes) == 1:
            self.dockwidget.groupContent.setText(classes[0])
        else:
            self.iface.messageBar().pushMessage("Warning", f"For {item.text()} there are no lc class to aggregate!", duration=3, level=Qgis.Warning)


    def loadGroups(self, json_path):
        """Clear ListWidget. Load groups from json file and display them in ListWidget."""

        self.groups = {}
        self.dockwidget.groupContent.clear()
        self.dockwidget.groupNames.clear()
        try:
            with open(json_path) as json_file:
                try:
                    self.groups = json.load(json_file)
                except ValueError as e:
                    self.iface.messageBar().pushMessage("Warning", f'Invalid json file: {e}', duration=5, level=Qgis.Warning)
                    return
            keys_list = list(self.groups.keys())
            self.dockwidget.groupNames.addItems(keys_list)
        except FileNotFoundError as e:
            pass


    def loadCountries(self, csv_file):
        """Load country codes from internal CSV file.

        :param str csv_file: path to CSV file

        :return list: list of country names and country codes
        """

        with open(csv_file, newline='') as csv_f:
            layer_reader = csv.DictReader(csv_f, delimiter=';')
            # collect country codes
            countries = []
            codes = []
            for row in layer_reader:
                codes.append(row['code'])
                countries.append(row['country'])

        return [codes, countries]


    def fillComboBox(self):
        """Fill combo box with names of countries."""

        # Clear combo box if it contains something
        self.dockwidget.countryNames.clear()

        # Fill Combo box with values
        for layer in self._countries_list[1]:
            self.dockwidget.countryNames.addItem(layer)


    def check(self):
        """Check which radio button is checked and enable/disable features according to it."""

        # AOI defile current canvas
        if self.dockwidget.curCanvas.isChecked():
            self.dockwidget.activeLayers.setEnabled(False)
            self.dockwidget.countryNames.setEnabled(False)
            self.dockwidget.countryNames.clear()

        # AOI define county (attribute NUTS0)
        elif self.dockwidget.country.isChecked():
            self.dockwidget.activeLayers.setEnabled(False)
            self.dockwidget.countryNames.setEnabled(True)

        # AOI define vector layer loaded into canvas
        elif self.dockwidget.vectorLayers.isChecked():
            self.dockwidget.activeLayers.setEnabled(True)
            self.dockwidget.countryNames.setEnabled(False)
            self.dockwidget.countryNames.clear()


    def checkYear(self):
        """Find out which years are checked.

        :return list: list of checked years
        """

        year_status = []

        if self.dockwidget.year06.isChecked():
            year_status.append(2006)

        if self.dockwidget.year09.isChecked():
            year_status.append(2009)

        if self.dockwidget.year12.isChecked():
            year_status.append(2012)

        if self.dockwidget.year15.isChecked():
            year_status.append(2015)

        if self.dockwidget.year18.isChecked():
            year_status.append(2018)

        if len(year_status) > 0:
            return year_status
        elif self.dockwidget.yearAll.isChecked():
            return [2006, 2009, 2012, 2015, 2018]
        else:
            return None

    def onDownload(self):
        """Initialize progress bar and run progressTask."""
        try:
            check_owslib()
        except LucasOWSLibError as e:
            iface.messageBar().pushMessage(
                f'Unsupported OWSLib version! Visit <a href="https://geoforall.fsv.cvut.cz/st_lucas/qgis_plugin/#known-issues">plugin documentation</a>.',
                duration=15, level=Qgis.Critical
            )
            return

        if self.checkInputs():
            return

        if self.dockwidget.outputDir.filePath():
            out_path = self.dockwidget.outputDir.filePath()
        else:
            iface.messageBar().clearWidgets()
            self.iface.messageBar().pushMessage("Error", "No output path was chosen!", level=Qgis.Critical)
            return

        if self.dockwidget.vectorLayers.isChecked():
            if self.layerToGml():
                gml_filter = self.layerToGml()
            else:
                return
        else:
            gml_filter = False

        # Get list of country codes which were selected.
        country_codes = []
        for element in self.dockwidget.countryNames.checkedItems():
            country_codes.append(self._countries_list[0][(self._countries_list[1].index(element))])

        # remove layer if exists
        layers = QgsProject.instance().mapLayersByName(self.layerName(out_path))
        if layers:
            # one layer expected
            QgsProject.instance().removeMapLayer(layers[0])

        # create download task
        task = progressTask(out_path, self.dockwidget.curCanvas.isChecked(), country_codes,
                            self.checkYear(), self.dockwidget.stAggregation.isChecked(), self.getLayerName(),
                            gml_filter)
        if platform.system() != 'Windows':
            # Initialize progress bar.
            progress_message_bar = iface.messageBar().createMessage("")
            progress = QProgressBar()
            progress.setMaximum(100)
            progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            progress_message_bar.layout().addWidget(progress)
            iface.messageBar().pushWidget(progress_message_bar, Qgis.Info)

            task.progressChanged.connect(lambda: progress.setValue(int(task.progress())))
            task.taskCompleted.connect(self.loadData)
            self.task_manager.addTask(task)
        else:
           # iface.messageBar().pushMessage('Downloading LUCAS points...', duration=5, level=Qgis.Info)
           # run in main thread
           # https://lists.osgeo.org/pipermail/qgis-developer/2025-January/067283.html
            QgsApplication.setOverrideCursor(Qt.WaitCursor)
            task.run()
            task.finished(None)
            self.loadData()
            QgsApplication.restoreOverrideCursor()

    def layerName(self, data_path):
        """Get layer name from data path."""
        return Path(data_path).stem

    def loadData(self):
        """Load downloaded data into map canvas."""
        data_path = self.dockwidget.outputDir.filePath()
        layer = QgsVectorLayer(data_path, self.layerName(data_path), "ogr")
        # set style
        qml_folder = Path(__file__).parent / 'style'
        qml_file = None
        if self._isLucasLayer(data_path, checkST=True):
            qml_file = os.path.join(qml_folder, 'lucas_st_aggregation_style.qml')
        else:
            if layer.fields().indexFromName('lc1_h') != -1:
                qml_file = os.path.join(qml_folder, 'lucas_style_lvl1.qml')
        if qml_file is not None:
            layer.loadNamedStyle(qml_file)
            layer.saveStyleToDatabase(qml_file, "", True, "")
        # add layer to map canvas & zoom
        QgsProject.instance().addMapLayer(layer)
        exform = QgsCoordinateTransform(layer.crs(),
                                        iface.mapCanvas().mapSettings().destinationCrs(),
                                        QgsProject.instance())
        iface.mapCanvas().setExtent(exform.transform(layer.extent()))
        iface.mapCanvas().refresh()


    def layerToGml(self):
        """Create GML string with coordinates of selected polygon vertices.

        :return str: GML which define polygon
        """

        cur_layer = self.dockwidget.activeLayers.currentLayer()
        if cur_layer.isEditable():
            iface.messageBar().clearWidgets()
            self.iface.messageBar().pushMessage("Error", "Layer is in editing mode!", level=Qgis.Critical)
            return
        features = cur_layer.getFeatures()
        cur_epsg = int(cur_layer.crs().authid().split(':')[1])
        if cur_layer.featureCount() == 1:
            filterxml = '<Within><PropertyName>lucas:geom</PropertyName><gml:Polygon xmlns:gml="http://www.opengis.net/gml" srsName="urn:ogc:def:crs:EPSG::3035" gml:id="polygon_32.geom.0"><gml:exterior><gml:LinearRing><gml:posList>'

            if cur_epsg != 3035:
                sourceCrs = QgsCoordinateReferenceSystem.fromEpsgId(cur_epsg)
                destCrs = QgsCoordinateReferenceSystem.fromEpsgId(3035)
                tr_parameters = QgsCoordinateTransform(sourceCrs, destCrs, QgsProject.instance())

            for feature in features:
                if cur_layer.wkbType() == 6:
                    if cur_epsg == 3035:
                        polygon = feature.geometry().asMultiPolygon()[0][0]
                    else:
                        polygon = feature.geometry()
                        polygon.transform(tr_parameters)
                        polygon = polygon.asMultiPolygon()[0][0]
                    num_vertices = len(polygon)
                    if len(feature.geometry().asMultiPolygon()) > 1:
                        self.iface.messageBar().pushMessage("Warning", "Only one part of multipolygon is used!",
                                                            level=Qgis.Warning)
                else:
                    if cur_epsg == 3035:
                        polygon = feature.geometry().asPolygon()[0]
                    else:
                        polygon = feature.geometry()
                        polygon.transform(tr_parameters)
                        polygon = polygon.asPolygon()[0]
                    num_vertices = len(polygon)

                for steps in range(num_vertices):
                    filterxml += f'{polygon[steps][1]} {polygon[steps][0]} '
                filterxml += '</gml:posList></gml:LinearRing></gml:exterior></gml:Polygon></Within>'

            return filterxml

        elif cur_layer.featureCount() > 1:
            iface.messageBar().clearWidgets()
            self.iface.messageBar().pushMessage("Error", "Layer has more than one feature!", level=Qgis.Critical)
            return

        else:
            iface.messageBar().clearWidgets()
            self.iface.messageBar().pushMessage("Error", "Layer has no feature!", level=Qgis.Critical)
            return


    def getLayerName(self):
        """Decide which WFS layer is required.

        :return str: name of WFS layer
        """

        if self.dockwidget.lclu.isChecked():
            return 'LC_LU'
        if self.dockwidget.lcluSoil.isChecked():
            return 'LC_LU_SO'
        if self.dockwidget.forestry.isChecked():
            return 'FO'
        if self.dockwidget.copernicus.isChecked():
            return 'CO'
        if self.dockwidget.inspire.isChecked():
            return 'IN'
        if self.dockwidget.all.isChecked():
            return None



    def checkInputs(self):
        """Check if everything required is defined.

        :return bool: False if all inputs are defined and request can be built
        """

        if not(self.dockwidget.curCanvas.isChecked() or self.dockwidget.country.isChecked() or self.dockwidget.vectorLayers.isChecked()):
            iface.messageBar().clearWidgets()
            self.iface.messageBar().pushMessage("Error", "No Area of interest was chosen!", level=Qgis.Critical)
            return True

        elif self.dockwidget.country.isChecked() and (not(self.dockwidget.countryNames.checkedItems())):
            iface.messageBar().clearWidgets()
            self.iface.messageBar().pushMessage("Error", "No country was selected!", level=Qgis.Critical)
            return True

        elif self.dockwidget.vectorLayers.isChecked() and self.dockwidget.activeLayers.currentLayer() is None:
            iface.messageBar().clearWidgets()
            self.iface.messageBar().pushMessage("Error", "No layer was selected!", level=Qgis.Critical)
            return True

        if self.dockwidget.curCanvas.isChecked():
            epsg = QgsProject.instance().crs().authid().split(':')[1]
            if int(epsg) != 3035:
                self.iface.messageBar().pushMessage("Warning", "Canvas bounding box will be transformed into LAEA Europe (EPSG: 3035), downloaded points may not exactly cover the selected canvas",
                                                    level=Qgis.Warning)
                return False

        return False

    def onPushButtonNext(self):
        curr_index = self.dockwidget.comboBoxPhoto.currentIndex()
        self.dockwidget.comboBoxPhoto.setCurrentIndex(curr_index + 1)
    
    def onPushButtonBack(self):
        curr_index = self.dockwidget.comboBoxPhoto.currentIndex()
        self.dockwidget.comboBoxPhoto.setCurrentIndex(curr_index - 1)
        
    def setBackNextButtons(self):
        if self.getPhotoUrl() is not None:
            if 1 < self.dockwidget.comboBoxPhoto.currentIndex() < 5:
                self.dockwidget.pushButtonBack.setEnabled(True)
                self.dockwidget.pushButtonNext.setEnabled(True)
                if self.dockwidget.comboBoxPhoto.currentIndex() == 2:
                    self.dockwidget.currentPhotoLabel.setText('North')
                if self.dockwidget.comboBoxPhoto.currentIndex() == 3:
                    self.dockwidget.currentPhotoLabel.setText('South')
                if self.dockwidget.comboBoxPhoto.currentIndex() == 4:
                    self.dockwidget.currentPhotoLabel.setText('West')
            elif self.dockwidget.comboBoxPhoto.currentIndex() == 1:
                self.dockwidget.pushButtonBack.setEnabled(False)
                self.dockwidget.pushButtonNext.setEnabled(True)
                self.dockwidget.currentPhotoLabel.setText('Point')
            elif self.dockwidget.comboBoxPhoto.currentIndex() == 5:
                self.dockwidget.pushButtonBack.setEnabled(True)
                self.dockwidget.pushButtonNext.setEnabled(False)
                self.dockwidget.currentPhotoLabel.setText('East')
        else:
            self.dockwidget.pushButtonBack.setEnabled(False)
            self.dockwidget.pushButtonNext.setEnabled(False)
            self.dockwidget.currentPhotoLabel.setText('')

    def clearPhoto(self):
        self.dockwidget.labelPhoto.clear()
    
    def showPhotoInBrowser(self):
        if self.dockwidget.comboBoxPhoto.currentIndex() == 0:
            iface.messageBar().pushMessage('Please select photo to be shown', duration=5, level=Qgis.Info)
        else:
            photo_url = self.getPhotoUrl()
            if photo_url != None:
                webbrowser.open(photo_url)
        
    def showPhotoInPlugin(self):
        self.dockwidget.labelPhoto.clear()
        photo_url = self.getPhotoUrl()
        if self.dockwidget.comboBoxPhoto.currentIndex() == 0:
            iface.messageBar().pushMessage('Please select photo to be shown', duration=5, level=Qgis.Info)
        if photo_url is not None:
            width = self.dockwidget.labelPhoto.width()
            height = self.dockwidget.labelPhoto.height()
            url_data = urlopen(photo_url).read()
            pixmap = QPixmap()
            pixmap.loadFromData(url_data)
            resized_pixmap = pixmap.scaled(width, height, Qt.KeepAspectRatio, Qt.FastTransformation)
            self.dockwidget.labelPhoto.setPixmap(resized_pixmap)
        else:
            self.dockwidget.labelLC.setText('')
            self.dockwidget.labelID.setText('')
            self.dockwidget.labelYear.setText('')

    def checkFeatureSelection(self):
        """Check feature selection."""
        layer_path, layer = self.getLayerPath()
        if self._isLucasLayer(layer_path, checkST=True) is True:
            iface.messageBar().pushMessage('Cannot show photos of space-time aggregated data', duration=5,
                                           level=Qgis.Warning)
            return False
        if self.dockwidget.comboBoxPhoto.currentIndex() == 0:
            return False

        if layer.selectedFeatureCount() > 1:
            iface.messageBar().pushMessage('Only one LUCAS point can be selected', duration=5,
                                           level=Qgis.Warning)
            return False
        if layer.selectedFeatureCount() == 0:
            iface.messageBar().pushMessage('No LUCAS point is selected', duration=5, level=Qgis.Warning)
            return False

        return True

    def getPhotoUrl(self):
        img_url = None
        if self.isLayerValid():
            layer_path, layer = self.getLayerPath()
            if self.checkFeatureSelection():
                feature = layer.selectedFeatures()
                point_id = feature[0]['point_id']
                year = feature[0]['survey_year']
                lc = feature[0]['lc1_h']
                lc_csv_file = os.path.join(os.path.dirname(__file__), "lc1.csv")
                with open(lc_csv_file, newline='') as csv_f:
                    layer_reader = csv.DictReader(csv_f, delimiter=';')
                    for row in layer_reader:
                        if row['code'] == lc:
                            lc_name = row['name']
                            break
                self.dockwidget.labelLC.setText('LUCAS LC class: ' + lc + ' - ' + lc_name)
                self.dockwidget.labelID.setText('LUCAS point ID: ' + str(point_id))
                self.dockwidget.labelYear.setText('Year of measurement: ' + str(year))
                imgs = LucasIO()
                imgs.data = layer_path
                imgs_url = imgs.get_images(year, point_id)
                if self.dockwidget.comboBoxPhoto.currentIndex() == 1:
                    img_url = imgs_url['P']
                elif self.dockwidget.comboBoxPhoto.currentIndex() == 2:
                    img_url = imgs_url['N']
                elif self.dockwidget.comboBoxPhoto.currentIndex() == 3:
                    img_url = imgs_url['S']
                elif self.dockwidget.comboBoxPhoto.currentIndex() == 4:
                    img_url = imgs_url['W']
                elif self.dockwidget.comboBoxPhoto.currentIndex() == 5:
                    img_url = imgs_url['E']
                else:
                    img_url = None
                if img_url is not None:
                    if requests.get(img_url).status_code != 200:
                        iface.messageBar().pushMessage('Selected photo is not available. Try another one.', duration=5, level=Qgis.Warning)
                        self.dockwidget.labelLC.setText('')
                        self.dockwidget.labelID.setText('')
                        self.dockwidget.labelYear.setText('')
                        img_url = None
        
        return img_url

    def downloadPhotos(self):
        if self.isLayerValid():
            layer_path, layer = self.getLayerPath()

            if self.checkFeatureSelection():
                feature = layer.selectedFeatures()[0]
                if feature['photo_point'] == 1 or feature['photo_north'] == 1 or feature['photo_east'] == 1 or feature['photo_south'] == 1 or feature['photo_west'] == 1:
                    save_dir = QFileDialog.getExistingDirectory(None, "Choose Directory to Store the Photos of Selected LUCAS Point")
                    if save_dir:
                        iface.messageBar().pushMessage('Downloading photos of selected LUCAS point...', level=Qgis.Info)
                        QCoreApplication.processEvents()
                        point_id = feature['point_id']
                        year = feature['survey_year']
                        images = LucasIO()
                        images.data = layer_path
                        images_url = images.get_images(year, point_id)
                        file_path = images.download_images(images_url, save_dir)
                        iface.messageBar().clearWidgets()
                        QCoreApplication.processEvents()
                        iface.messageBar().pushMessage(f'Photos of selected LUCAS point were downloaded: {file_path}',
                                                       duration=5, level=Qgis.Info)
                else:
                    iface.messageBar().pushMessage('Selected LUCAS point does not have any photos',
                                                   duration=5, level=Qgis.Warning)
    
    def fillColumnComboBox(self):
        """Fill combo box with names of CSV columns."""

        # Clear combo box if it contains something
        self.dockwidget.columnComboBox.clear()

        # Fill Combo box with values
        with open(self.dockwidget.csvPath.filePath()) as csv_file:
            csv_reader = csv.DictReader(csv_file)
            dict_from_csv = dict(list(csv_reader)[0])
            list_of_column_names = list(dict_from_csv.keys())
            self.dockwidget.columnComboBox.addItem(list_of_column_names[2])

    
    def onTranslationApply(self):
        if self.isLayerValid():
            layer_path, layer = self.getLayerPath()
            try:
                translation = LucasClassTranslate(
                    gpkg_path,
                    csvpath=self.dockwidget.csvPath.filePath()
                )
                try:
                    col_name = self.dockwidget.columnComboBox.currentText()
                    translation.set_translations(col_name)
                    translation.apply()
                    layer = QgsVectorLayer(gpkg_path, "translated", "ogr") 
                    exform = QgsCoordinateTransform(layer.crs(),
                                                    iface.mapCanvas().mapSettings().destinationCrs(),
                                                    QgsProject.instance())
                    iface.mapCanvas().setExtent(exform.transform(layer.extent()))
                    iface.mapCanvas().refreshAllLayers()
                    self.iface.messageBar().pushMessage("Translation was successfully applied!", duration=5, level=Qgis.Success)
                except LucasLoadError as e:
                    self.iface.messageBar().pushMessage("Error", f'{e}', duration=5, level=Qgis.Critical)
                except LucasDataError as e:
                    self.iface.messageBar().pushMessage("Error", f'{e}', duration=5, level=Qgis.Critical)
            except LucasLoadError as e:
                self.iface.messageBar().pushMessage("Error", f"{e}", duration=5, level=Qgis.Critical)


    def setSpaceTimeAgg(self):
        if self.checkYear() is not None and len(self.checkYear()) > 1:
            self.dockwidget.stAggregation.setEnabled(True)
        else:
            self.dockwidget.stAggregation.setEnabled(False)
            self.dockwidget.stAggregation.setChecked(False)
    
    def setCheckedYears(self):
        if self.dockwidget.yearAll.isChecked():
            self.dockwidget.year06.setChecked(False)
            self.dockwidget.year09.setChecked(False)
            self.dockwidget.year12.setChecked(False)
            self.dockwidget.year15.setChecked(False)
            self.dockwidget.year18.setChecked(False)
            self.dockwidget.year06.setEnabled(False)
            self.dockwidget.year09.setEnabled(False)
            self.dockwidget.year12.setEnabled(False)
            self.dockwidget.year15.setEnabled(False)
            self.dockwidget.year18.setEnabled(False)
        else:
            self.dockwidget.year06.setEnabled(True)
            self.dockwidget.year09.setEnabled(True)
            self.dockwidget.year12.setEnabled(True)
            self.dockwidget.year15.setEnabled(True)
            self.dockwidget.year18.setEnabled(True)


class progressTask(QgsTask):
    points = pyqtSignal(int)

    def __init__(self, output_path, canvas, countries, checked_years, st_aggregation, layer_name, vector_filter):
        self._output_path = output_path
        self._canvas = canvas
        self._countries = countries
        self._years = checked_years
        self._st_aggregation = st_aggregation
        self._layer_name = layer_name
        self.error = None
        self.warning = None

        self._vector_filter = vector_filter
        super().__init__()

        self._downloader = None

    def finished(self, result):
        self.setProgress(100)
        iface.messageBar().clearWidgets()
        if self.error:
            iface.messageBar().clearWidgets()
            iface.messageBar().pushMessage(f'Points weren\'t downloaded: {self.error}!', duration=5, level=Qgis.Critical)
        else:
            if self.warning:
                iface.messageBar().pushMessage('Warning', self.warning, duration=10, level=Qgis.Warning)
            points_number = self._downloader.count()
            if points_number == 1:
                iface.messageBar().pushMessage('{} {}'.format(points_number, 'point was downloaded!'), duration=5, level=Qgis.Success)
            else:
                iface.messageBar().pushMessage('{} {}'.format(points_number, 'points were downloaded!'), duration=5, level=Qgis.Success)

    def run(self):
        """Build request for WFS and download data in selected data type."""
        self.setProgress(10)
        req = LucasRequest()

        try:
            if self._layer_name:
                req.group = self._layer_name

            req.st_aggregated = self._st_aggregation

            req.years = self._years
            if req.years is None:
                self.error = 'No year is checked'
                return

            if self._canvas:
                # BBOX filter
                canvas_coordinates = (iface.mapCanvas().extent())
                epsg = int(QgsProject.instance().crs().authid().split(':')[1])
                if epsg != 3035:
                    source_crs = QgsCoordinateReferenceSystem.fromEpsgId(epsg)
                    target_crs = QgsCoordinateReferenceSystem.fromEpsgId(3035)
                    transform = QgsCoordinateTransform(source_crs, target_crs, QgsProject.instance())
                    canvas_coordinates = transform.transformBoundingBox(canvas_coordinates)
                req.bbox = (int(canvas_coordinates.xMinimum()), int(canvas_coordinates.yMinimum()), int(canvas_coordinates.xMaximum()), int(canvas_coordinates.yMaximum()))

            elif any(self._countries):
                # Country filter
                req.countries = self._countries
                
            elif self._vector_filter:
                req.aoi_polygon = self._vector_filter
        except LucasRequestError as e:
            self.error = e
            return


        self.setProgress(20)

        self._downloader = LucasIO()

        try:
            self._downloader.download(req)
        except (LucasRequestError, LucasDownloadError, LucasDataError) as e:
            self.error = e
            return

        self.setProgress(60)

        try:
            self._downloader.to_gpkg(self._output_path)
        except (LucasDataError, LucasDownloadError) as e:
            self.error = e
            return

        self.setProgress(80)

        if self.error is None:
            try:
                if self._downloader.is_empty():
                    self.warning = 'No point matches the selected parameters.'
                else:
                    features_num = self._downloader.count()
                    self.points.emit(features_num)
                    if features_num == int(self._downloader.metadata['LUCAS_MAX_FEATURES']):
                        self.warning = 'Limit for download is ' + metadata['LUCAS_MAX_FEATURES'] + ' points. All required points probably weren\'t downloaded.'
            except LucasDataError as e:
                self.error = e
                return

        return True
