# -*- coding: utf-8 -*-
"""
/***************************************************************************
 SaveAttributes
                                 A QGIS plugin
 SaveAttributes
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2019-03-31
        git sha              : $Format:%H$
        copyright            : (C) 2019 by rui
        email                : ucesrji@ucl.ac.uk
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 PyQt5.QtCore import QSettings, QTranslator, qVersion, QCoreApplication
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QAction, QFileDialog
from qgis.core import QgsProject, Qgis, QgsVectorLayer,QgsDataSourceUri,QgsVectorFileWriter,QgsWkbTypes

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

class SaveAttributes:
    """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',
            'SaveAttributes_{}.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'&Save Attributes')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('SaveAttributes', message)


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.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/save_attributes/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Save Attributes as CSV'),
            callback=self.run,
            parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginVectorMenu(
                self.tr(u'&Save Attributes'),
                action)
            self.iface.removeToolBarIcon(action)


  #  def list_all_sites(self):
  #      conn = psycopg2.connect(
  #          host="localhost",
  #          port=5432,
  #          dbname="postgis_dt",
  #          user="postgres",
  #          password="Jr19951123"
  #      )
        # site
  #      cur = conn.cursor()
  #      cur.execute("""select * from dt.site;""")
  #      sites = cur.fetchall()
  #      list_of_sites = []
  #      for site in sites:
  #          # print (i)
            #  print (site[1])
  #          list_of_sites.append(site[1])
  #      conn.commit()
        # Clear the contents of the comboBox from previous runs
  #      self.dlg.comboBox_2.clear()
        # Populate the comboBox with names of all the loaded layers
        #  self.dlg.comboBox.addItems([layer.name() for layer in layers])
  #      self.dlg.comboBox_2.addItems(list_of_sites)

    def list_all_related_topics(self):
        site_name = str(self.dlg.comboBox_2.currentText())
        # connect to the database
        try:
            conn = psycopg2.connect(
                host="developer.cege.ucl.ac.uk",
                port=33029,
                dbname="user20db",
                user="user20",
                password="Jr19951123"
            )
        except:
            conn = psycopg2.connect(
                host="localhost",
                port=5432,
                dbname="postgis_dt",
                user="postgres",
                password="Jr19951123"
            )
        cur = conn.cursor()
        cur.execute("""select c.site_name,b.topic_name
        from dt.site c 
        inner join dt.site_topic a 
        on c.site_id = a.site_id 
        inner join dt.topic b 
        on a.topic_id = b.topic_id where site_name = '""" + site_name + """';""")
        topics = cur.fetchall()
        list_of_topics = []
        for topic in topics:
            # print (i)
            #  print (site[1])
            list_of_topics.append(topic[1])
        conn.commit()
        # Clear the contents of the comboBox from previous runs
        self.dlg.comboBox_3.clear()
        self.dlg.listWidget.clear()
        #self.dlg.comboBox_4.clear()
        # Populate the comboBox with names of all the loaded layers
        #  self.dlg.comboBox.addItems([layer.name() for layer in layers])
        self.dlg.comboBox_3.addItems(list_of_topics)

    def list_all_related_layers(self):
        topic_name = str(self.dlg.comboBox_3.currentText())
        # connect to the database
        try:
            conn = psycopg2.connect(
                host="developer.cege.ucl.ac.uk",
                port=33029,
                dbname="user20db",
                user="user20",
                password="Jr19951123"
            )
        except:
            conn = psycopg2.connect(
                host="localhost",
                port=5432,
                dbname="postgis_dt",
                user="postgres",
                password="Jr19951123"
            )
        cur = conn.cursor()

        cur.execute("""select a.topic_name,b.layer_name
        from dt.topic a 
        inner join dt.layer b 
        on a.topic_id = b.topic_id
        where topic_name  = '""" + topic_name + """';""")

        layers = cur.fetchall()
        list_of_layers=[]
        for layer in layers:
            list_of_layers.append(layer[1])

        conn.commit()

        # Clear the contents of the comboBox from previous runs
        #self.dlg.comboBox_4.clear()

        # Populate the comboBox with names of all the loaded layers
        #  self.dlg.comboBox.addItems([layer.name() for layer in layers])
        #self.dlg.comboBox_4.addItems(list_of_layers)
        self.dlg.listWidget.clear()
        for i in list_of_layers:
            self.dlg.listWidget.addItem(i)


    def confirm_site_topic_layer(self):
        site_name = str(self.dlg.comboBox_2.currentText())
        topic_name = str(self.dlg.comboBox_3.currentText())
        #layer_name = str(self.dlg.comboBox_4.currentText())
        layer_name = str(self.dlg.listWidget.currentItem().text())
        information1 = "Development site: " + site_name + "."
        information2 = "Topic: " + topic_name + "."
        information3 = "Environmental layer: " + layer_name + "."
        self.dlg.lineEdit_4.setText(information1)
        self.dlg.lineEdit_5.setText(information2)
        self.dlg.lineEdit_6.setText(information3)


    def load_site_shp(self):
        site_name = str(self.dlg.comboBox_2.currentText())
        uri = QgsDataSourceUri()
        # set host name, port, database name, username and password
        uri.setConnection("developer.cege.ucl.ac.uk", "33029", "user20db", "user20", "Jr19951123")
        # set database schema, table name, geometry column and optionally
        uri.setDataSource("shp_dt", site_name, "geom")
        vlayer = QgsVectorLayer(uri.uri(False), site_name, "postgres")
        QgsProject.instance().addMapLayer(vlayer)
        canvas = self.iface.mapCanvas()
        extent = vlayer.extent()
        canvas.setExtent(extent)

        text = site_name + " loaded!"
        self.dlg.lineEdit_2.setText(text)


    def load_env_shp(self):
        #layer_name = str(self.dlg.comboBox_4.currentText())
        layer_name = str(self.dlg.listWidget.currentItem().text())
        uri = QgsDataSourceUri()
        # set host name, port, database name, username and password
        uri.setConnection("developer.cege.ucl.ac.uk", "33029", "user20db", "user20", "Jr19951123")
        # set database schema, table name, geometry column and optionally
        # subset (WHERE clause)
        uri.setDataSource("shp_dt", layer_name, "geom")
        vlayer = QgsVectorLayer(uri.uri(False), layer_name, "postgres")
        QgsProject.instance().addMapLayer(vlayer)

        text = layer_name + " loaded!"
        self.dlg.lineEdit_2.setText(text)

    def show_buff_distance(self):
        buff_distance = self.dlg.spinBox.value()
        unit = str(self.dlg.comboBox.currentText())
        self.dlg.lineEdit_7.setText(str(buff_distance)+' '+unit)


    def display_buff_on_maps(self):
        buffer_distance = self.dlg.spinBox.value()
        unit = str(self.dlg.comboBox.currentText())
        site_name = str(self.dlg.comboBox_2.currentText())
        output_path = self.dlg.lineEdit_3.text()
        outFn = str(output_path)
        #outFn = str('D:/aaaaa/DT/temp/'+site_name+'_'+str(buffer_distance)+'_'+unit+'_buffer'+'.shp')
        layers = QgsProject.instance().mapLayersByName(site_name)
        layer = layers[0]
        fields = layer.fields()
        feats = layer.getFeatures()
        writer = QgsVectorFileWriter(outFn, 'UTF-8', fields, QgsWkbTypes.Polygon, layer.sourceCrs(), 'ESRI Shapefile')
        if unit == "metre":
            buffer_distance = buffer_distance
        if unit == "kilometres":
            buffer_distance = buffer_distance*1000
        if unit == "feet":
            buffer_distance = buffer_distance*0.3048
        if unit == "miles":
            buffer_distance = buffer_distance*1609.344
        for feat in feats:
            geom = feat.geometry()
            buff = geom.buffer(buffer_distance, 5)
            feat.setGeometry(buff)
            writer.addFeature(feat)
        #self.iface.addVectorLayer(layer, '', 'ogr')
        self.iface.addVectorLayer(outFn, '', 'ogr')
        #QgsProject.instance().addMapLayer(outFn)
        #QgsProject.instance().addMapLayer(layer)
        del writer

    def select_output_file(self):
        filename, _filter = QFileDialog.getSaveFileName(
            self.dlg, "Select   output file ","", '*.shp')
        self.dlg.lineEdit_3.setText(filename)

    def run(self):
        """Run method that performs all the real work"""

        # connect to the database
        try:
            conn = psycopg2.connect(
                host="developer.cege.ucl.ac.uk",
                port=33029,
                dbname="user20db",
                user="user20",
                password="Jr19951123"
            )
        except:
            conn = psycopg2.connect(
                host="localhost",
                port=5432,
                dbname="postgis_dt",
                user="postgres",
                password="Jr19951123"
            )
        # ## 2. Execute query

        # ### 2.1 List all topics

        # site
        cur = conn.cursor()
        cur.execute("""select * from dt.site;""")
        sites = cur.fetchall()
        list_of_sites = []
        for site in sites:
            # print (i)
            #  print (site[1])
            list_of_sites.append(site[1])
        conn.commit()

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            #self.dlg = connect_to_database()
            self.dlg = SaveAttributesDialog()
          #  self.dlg.pushButton_2.clicked.connect(self.list_all_sites)
            self.dlg.pushButton_4.clicked.connect(self.list_all_related_topics)
            self.dlg.pushButton_3.clicked.connect(self.list_all_related_layers)
            self.dlg.pushButton_5.clicked.connect(self.confirm_site_topic_layer)
            self.dlg.pushButton_8.clicked.connect(self.load_site_shp)
            self.dlg.pushButton_2.clicked.connect(self.load_env_shp)
            self.dlg.pushButton_10.clicked.connect(self.show_buff_distance)
            self.dlg.pushButton_9.clicked.connect(self.display_buff_on_maps)
            self.dlg.pushButton.clicked.connect(self.select_output_file)
            self.dlg.pushButton_6.clicked.connect(self.select_output_file)

		# Fetch the currently loaded layers
        layers = QgsProject.instance().layerTreeRoot().children()
		# Clear the contents of the comboBox from previous runs
        self.dlg.comboBox_2.clear()
		# Populate the comboBox with names of all the loaded layers
		# Populate the comboBox with names of all the loaded layers
      #  self.dlg.comboBox.addItems([layer.name() for layer in layers])
        self.dlg.comboBox_2.addItems(list_of_sites)


        list_of_units = ['metres', 'kilometres','feet','miles']
        self.dlg.comboBox.clear()
        # Populate the comboBox with names of all the loaded layers
        # Populate the comboBox with names of all the loaded layers
        #  self.dlg.comboBox.addItems([layer.name() for layer in layers])
        self.dlg.comboBox.addItems(list_of_units)

        # show the dialog
        self.dlg.show()


        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            filename = self.dlg.lineEdit.text()
            with open(filename, 'w') as output_file:
                selectedLayerIndex = self.dlg.comboBox.currentIndex()
                selectedLayer = layers[selectedLayerIndex].layer()
                fieldnames = [field.name() for field in selectedLayer.fields()]
                # write header
                line = ','.join(name for name in fieldnames) + '\n'
                output_file.write(line)
                # wirte feature attributes
                for f in selectedLayer.getFeatures():
                    line = ','.join(str(f[name]) for name in fieldnames) + '\n'
                    output_file.write(line)
            self.iface.messageBar().pushMessage(
                "Success", "Output file written at " + filename,
                level=Qgis.Success, duration=3)