# -*- 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
from tempfile import mkstemp
import json
from os import path
from osgeo import gdal

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

from qgis.core import Qgis, QgsTask, QgsApplication, QgsVectorLayer, QgsProject, QgsMapLayerProxyModel, QgsCoordinateReferenceSystem, QgsCoordinateTransform
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

# Import owslib
from owslib.fes import PropertyIsEqualTo, Or

import requests
from urllib.request import urlopen

import webbrowser

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

        # 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 = {}


    # 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)
                
                # 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 onGroupsApply(self):
        """Create new columns in which are aggregated LC1 classes stored."""

        # gpkg_path = self.dockwidget.outputDir.filePath()
        nlayers = len(iface.layerTreeView().selectedLayers())
        if nlayers == 0:
            iface.messageBar().pushMessage('No layer selected', duration=5, level=Qgis.Warning)
        elif nlayers > 1:
            iface.messageBar().pushMessage('Only one layer must be selected', duration=5, level=Qgis.Warning)
        else:
            layer = iface.layerTreeView().selectedLayers()[0]
            gpkg_path = layer.dataProvider().dataSourceUri().split("|")[0]
            ds = gdal.OpenEx(gpkg_path, gdal.OF_VECTOR)
            metadata = ds.GetMetadata()
            if 'LUCAS_CLIENT_VERSION' not in metadata.keys():
                iface.messageBar().pushMessage('Not valid LUCAS layer', duration=5, level=Qgis.Warning)
            else:
                try:
                    aggregation = LucasClassAggregate(
                        gpkg_path,
                        mappings_file=self.dockwidget.jsonPath.filePath()
                    )
                    try:
                        aggregation.apply()
                        layer = QgsVectorLayer(gpkg_path, "aggregated", "ogr")
                        extent = layer.extent()
                        iface.mapCanvas().setExtent(extent)
                        # iface.mapCanvas().refresh()
                        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)
                    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 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

        # 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)

        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))])

        task = progressTask(out_path, self.dockwidget.curCanvas.isChecked(), country_codes, self.checkYear(), self.dockwidget.stAggregation.isChecked(), self.getLayerName(), gml_filter)
        task.progressChanged.connect(lambda: progress.setValue(int(task.progress())))

        QgsApplication.taskManager().addTask(task)


    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_epsg == 3035:
            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>'

                for feature in features:
                    if cur_layer.wkbType() == 6:
                        polygon = feature.geometry().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:
                        polygon = feature.geometry().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
        else:
            iface.messageBar().clearWidgets()
            self.iface.messageBar().pushMessage("Error", "Layer projection should be LAEA Europe (EPSG: 3035)!", 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:
                iface.messageBar().clearWidgets()
                self.iface.messageBar().pushMessage("Error", "Project projection should be LAEA Europe (EPSG: 3035)!", level=Qgis.Critical)
                return True

        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 getPhotoUrl(self):
        img_url = None
        nlayers = len(iface.layerTreeView().selectedLayers())
        if nlayers == 0:
            iface.messageBar().pushMessage('No layer selected', duration=5, level=Qgis.Warning)
        elif nlayers > 1:
            iface.messageBar().pushMessage('Only one layer must be selected', duration=5, level=Qgis.Warning)
        else:
            layer = iface.layerTreeView().selectedLayers()[0]
            layer_path = layer.dataProvider().dataSourceUri().split("|")[0]
            ds = gdal.OpenEx(layer_path, gdal.OF_VECTOR)
            metadata = ds.GetMetadata()
            if 'LUCAS_CLIENT_VERSION' not in metadata.keys():
                iface.messageBar().pushMessage('Not valid LUCAS layer', duration=5, level=Qgis.Warning)
                return img_url
            if metadata['LUCAS_ST'] == '1':
                iface.messageBar().pushMessage('Cannot show photos of space-time aggregated data', duration=5, level=Qgis.Warning)
                return img_url
            if self.dockwidget.comboBoxPhoto.currentIndex() == 0:
                return img_url
            elif layer.selectedFeatureCount() > 1:
                iface.messageBar().pushMessage('Only one LUCAS point can be selected', duration=5, level=Qgis.Warning)
            elif layer.selectedFeatureCount() == 0:
                iface.messageBar().pushMessage('No LUCAS point is selected', duration=5, level=Qgis.Warning)
            else:
                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 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):
        nlayers = len(iface.layerTreeView().selectedLayers())
        if nlayers == 0:
            iface.messageBar().pushMessage('No layer selected', duration=5, level=Qgis.Warning)
        elif nlayers > 1:
            iface.messageBar().pushMessage('Only one layer must be selected', duration=5, level=Qgis.Warning)
        else:
            layer = iface.layerTreeView().selectedLayers()[0]
            gpkg_path = layer.dataProvider().dataSourceUri().split("|")[0]
            ds = gdal.OpenEx(gpkg_path, gdal.OF_VECTOR)
            metadata = ds.GetMetadata()
            if 'LUCAS_CLIENT_VERSION' not in metadata.keys():
                iface.messageBar().pushMessage('Not valid LUCAS layer', duration=5, level=Qgis.Warning)
            else:
                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")
                        extent = layer.extent()
                        iface.mapCanvas().setExtent(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.file_name = ""
        self._vector_filter = vector_filter
        super().__init__()

    def run(self):

        self.download()

        return True

    def finished(self, result):
        if self.error:
            iface.messageBar().clearWidgets()
            iface.messageBar().pushMessage(f'Points weren\'t downloaded: {self.error}!', duration=5, level=Qgis.Critical)
        else:
            layer = QgsVectorLayer(self._output_path, self.file_name, "ogr")
            ds = gdal.OpenEx(self._output_path, gdal.OF_VECTOR)
            metadata = ds.GetMetadata()
            iface.messageBar().clearWidgets()
            if metadata['LUCAS_ST'] == '1':
                iface.messageBar().pushMessage('No style for space-time aggregated data', duration=5)
            else:
                file_path = os.path.dirname(os.path.realpath(__file__))
                qml_folder = os.path.join(file_path, 'style')
                qml_file = os.path.join(qml_folder, 'lucas_style_lvl1.qml')
                layer.loadNamedStyle(qml_file)
                layer.saveStyleToDatabase(qml_file, "", True, "")
            QgsProject.instance().addMapLayer(layer)
            ex = layer.extent()
            iface.mapCanvas().setExtent(ex)
            iface.mapCanvas().refresh()
            self.setProgress(100)
            if self.warning:
                iface.messageBar().pushMessage('Warning', self.warning, duration=10, level=Qgis.Warning)
            else:
                points_number = layer.featureCount()
                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 download(self):
        """Build request for WFS and download data in selected data type."""

        self.setProgress(1)
        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())
                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)

        downloader = LucasIO()

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

        self.setProgress(40)

        f_name, file_extension = os.path.splitext(self._output_path)

        self.file_name = f_name.split("\\")[-1]

        """
        if file_extension == '.gml':
            with open(self._output_path, 'wb') as fd:
                fd.write(downloader.to_gml().encode('utf_8'))
        elif file_extension == '.gpkg':
        """

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

        self.setProgress(60)

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

        self.setProgress(80)
