# -*- coding: utf-8 -*-
"""
/***************************************************************************
 ParcelleToSite
								 A QGIS plugin
 Permet d'associer des parcelles à des sites
							  -------------------
		begin				: 2015-06-19
		git sha			  : $Format:%H$
		copyright			: (C) 2015 by CEN Savoie
		email				: a.lesconnec@cen-savoie.org
 ***************************************************************************/

/***************************************************************************
 *																		 *
 *   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 import QtCore, QtGui
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QAction, QTableWidgetItem, QApplication, QMessageBox

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

# Import the code for the dialog
from pluginsCenSavoie_v3.tools.parcelle_to_site_dialog import ParcelleToSiteDialog

# Import du fichier de configuration
from pluginsCenSavoie_v3.tools.confPython import bd_cen_host, bd_cen_port, bd_cen_name, bd_cen_mdp_1st_cnx

import os.path
import sys 
import qgis
import os
import psycopg2 
import psycopg2.extras
import base64
import re
from time import localtime, strftime

class ParcelleToSite:
	"""QGIS Plugin Implementation."""

	def __init__(self, iface, cenToolbar):
		"""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
		"""
		# Variable HOTE de l'accès à la base de données
		global host
		host = bd_cen_host
		global port
		port = bd_cen_port
		global bdd
		bdd = bd_cen_name
		global mdp_1st_cnx
		mdp_1st_cnx = bd_cen_mdp_1st_cnx
		global os_user
		if sys.platform == 'linux':
			os_user = os.environ['USER']
		else:
			os_user = os.environ['USERNAME']
		
		# Save reference to the QGIS interface
		self.iface = iface
		self.canvas = self.iface.mapCanvas()
		
		# initialize plugin directory
		self.plugin_dir = os.path.dirname(__file__)
		
		# Create the dialog (after translation) and keep reference
		self.dlg = ParcelleToSiteDialog()

		# Add toolbar button
		self.action= QAction(QIcon(":/plugins/pluginsCenSavoie_v3/icons/parcelleToSite.png"),  QCoreApplication.translate('ParcelleToSite', u'Associer des parcelles à un site'),  self.iface.mainWindow())
		self.action.triggered.connect(self.run)
		self.action.setEnabled(False)
		cenToolbar.addAction(self.action)
		self.canvas.selectionChanged.connect(self.toggle)
		self.iface.layerTreeView().currentLayerChanged.connect(self.toggle)

	def toggle(self):
		layer = self.iface.activeLayer()
		if layer and layer.type() == layer.VectorLayer:
			if layer.selectedFeatureCount() > 0:
				provider = layer.dataProvider()
				source_postgis = provider.dataSourceUri()
				source_postgis = source_postgis.replace('"', '')				
				if (source_postgis.count('table=cadastre.parcelles ') == 1 or source_postgis.count('table=cadastre.v_parcelles') == 1):
					self.action.setEnabled(True)
				else:
					self.action.setEnabled(False)
			else:
				self.action.setEnabled(False)
		else:
			self.action.setEnabled(False)
		
	def run(self):
		"""Run method that performs all the real work"""
		tbl_par_id = []
		self.canvas = self.iface.mapCanvas()
		global layer
		layer = self.iface.activeLayer()
		provider = layer.dataProvider()
		source_postgis = provider.dataSourceUri()
		source_postgis = source_postgis.replace('"', '')
		if (source_postgis.count('table=cadastre.parcelles ') != 1 and source_postgis.count('table=cadastre.v_parcelles_') != 1):
			self.action.setEnabled(False)
			QMessageBox.warning(None, "Oups:", str("La couche active n'est pas une couche parcelles valide"))
		else:			
			rowCount = 0
			for feature in layer.selectedFeatures():
				tbl_par_id.append(feature["par_id"])
							
			if (len(tbl_par_id) < 1):
				QMessageBox.warning(None, "Oups:", 'Selection invalide')
			else:
				first_conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=first_cnx password=" + mdp_1st_cnx)
				first_cur = first_conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
				first_cur.execute("SELECT mdp_cen, usename FROM pg_catalog.pg_user t1, admin_sig.utilisateurs t2 WHERE t2.oid = t1.usesysid AND (utilisateur_id = '" + os_user + "' OR utilisateur_os = '" + os_user + "')")
				res_ident = first_cur.fetchone()
				mdp = base64.b64decode(str(res_ident[0])).decode('utf-8')
				user = res_ident[1]
				first_conn.close()
				self.dlg.InitFormulaire(tbl_par_id, 'load', host, port, bdd, user, mdp)
				self.dlg.img_logo.setPixmap(QPixmap(":/plugins/pluginsCenSavoie_v3/tools/images/Logo_CEN_Savoie.png"))
				self.dlg.img_frise.setPixmap(QPixmap(":/plugins/pluginsCenSavoie_v3/tools/images/Frise_portrait.png"))
				self.dlg.img_frise.stackUnder(self.dlg.button_box)
				# 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.			
					conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
					cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
					QApplication.setOverrideCursor(Qt.WaitCursor)
					with conn:
						with conn.cursor() as cur:
							for feature in layer.selectedFeatures():
								rq_insert = """SELECT cadastre.import_parcelles_cen('"""+ str(feature["par_id"]) + """', '"""+ str(self.dlg.site_sel.text()) +"""', '"""+ str(self.dlg.lst_pci.currentText())  +"""')"""
								cur.execute(rq_insert)
								conn.commit()
							rq_refresh = """SELECT admin_sig.refresh_mview_foncier('"""+ str(self.dlg.site_sel.text()) +"""')"""
							cur.execute(rq_refresh)
							conn.commit()
					self.canvas.refresh()
					QApplication.restoreOverrideCursor()