# -*- coding: utf-8 -*-
"""
/***************************************************************************
 CreateSessionAFDialog
								 A QGIS plugin
 Permet de créer une nouvelle session d'animation foncière
							 -------------------
		begin				: 2015-10-02
		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.								   *
 *																		 *
 ***************************************************************************/
"""

import os
import psycopg2 
import psycopg2.extras
from PyQt5 import QtGui, uic
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QDialog, QMessageBox
from functools import partial 
import datetime
from time import localtime, strftime

FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'create_sessionAF_dialog_base.ui'))

class CreateSessionAFDialog(QDialog, FORM_CLASS):
	def __init__(self, parent=None):
		"""Constructor."""
		super(CreateSessionAFDialog, self).__init__(parent)
		self.setupUi(self)
		
	def InitFormulaire(self, tbl_site_id, rq_saf_geom, acces, host, port, bdd, user, mdp):
		self.lst_saf_maj.blockSignals(True)
		self.lst_saf_origin.blockSignals(True)
		self.saf_utilisateur.setText(user)
		aujourdhui = strftime("%Y-%m", localtime())		
		self.saf_date.setText(aujourdhui)
		k = 0
		nom = 'SAF_'
		while k < len(tbl_site_id):
			nom += tbl_site_id[k] + '_'
			k = k + 1
		nom += aujourdhui
		self.saf_name.setText(nom)
		
		global conn, cur
		conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
		cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
		
		with conn:
			with conn.cursor() as cur:
				# Initialisation de la liste de l'origine de la SAF					
				rq_saf_origines = "SELECT DISTINCT saf_origine_id, saf_origine_lib FROM animation_fonciere.d_saf_origines ORDER BY saf_origine_id"
				cur.execute(rq_saf_origines)
				res_saf_origines = cur.fetchall() 
				self.lst_saf_origin.clear() #Vidage de la combobox
				i = 0 #Déclaration à 0 d'une variable pour boucler sur toutes les options de la requête identifiée plus haut
				global tbl_saf_origin
				self.tbl_saf_origin = []
				self.lst_saf_origin.blockSignals(True)
				while i < len(res_saf_origines): #Boucle sur toutes les options
					id = res_saf_origines[i][0] #Déclaration de la variable stockant l'identifiant
					lib = res_saf_origines[i][1] #Déclaration de la variable stockant le libellé
					self.lst_saf_origin.addItem(lib)
					self.tbl_saf_origin.append(id)
					i+=1
				self.lst_saf_origin.setCurrentIndex(-1)	
				self.lst_saf_origin.blockSignals(False)
				self.saf_origin.setVisible(0)
				self.saf_origin.setText('N.P.')
				self.lst_saf_origin.currentIndexChanged.connect(self.chg_lst_saf_origin)
				
				# Initialisation de la liste des SAF modifiables
				rq_saf_maj = """
				SELECT *
				FROM 
					(
						SELECT DISTINCT 
							session_af_id, 
							session_af_lib,
							st_distance(session_af.geom, ("""+rq_saf_geom+""")) as dist,
							date_maj
						FROM 
							animation_fonciere.session_af
						
						ORDER BY dist, date_maj DESC
						LIMIT 10
					) t1
				WHERE
					dist < 5000"""
				cur.execute(rq_saf_maj)
				res_saf_maj = cur.fetchall()
				self.lst_saf_maj.blockSignals(True)
				if cur.rowcount > 0:
					self.lst_saf_maj.clear() #Vidage de la combobox
					i = 0 #Déclaration à 0 d'une variable pour boucler sur toutes les options de la requête identifiée plus haut
					global tbl_saf_maj
					self.tbl_saf_maj = []
					while i < len(res_saf_maj): #Boucle sur toutes les options
						id = res_saf_maj[i][0] #Déclaration de la variable stockant l'identifiant
						lib = res_saf_maj[i][1] #Déclaration de la variable stockant le libellé
						self.lst_saf_maj.addItem(lib)
						self.tbl_saf_maj.append(id)
						i+=1
					self.lst_saf_maj.setCurrentIndex(-1)
					self.lst_saf_maj.blockSignals(False)
					self.saf_maj.setVisible(0)
					self.saf_maj.setText('N.P.')
					self.lst_saf_maj.setEnabled(True)
					self.lst_saf_maj.currentIndexChanged.connect(self.chg_lst_saf_maj)
				else:
					self.lst_saf_maj.setCurrentIndex(-1)
					self.saf_maj.setVisible(0)
					self.saf_maj.setText('N.P.')
					self.lst_saf_maj.setEnabled(False)
		self.button_box.setEnabled(False)
		self.lst_saf_maj.blockSignals(False)
		self.lst_saf_origin.blockSignals(False)
		
	def chg_lst_saf_origin(self, index):
		self.lst_saf_maj.blockSignals(True)
		self.lst_saf_origin.blockSignals(True)
		
		if len(self.tbl_saf_origin)>0 and self.tbl_saf_origin[index] and index>-1:
			self.saf_origin.setText(str(self.tbl_saf_origin[index]))
			
			self.lst_saf_maj.setCurrentIndex(-1)
			self.saf_maj.setText('N.P.')
			
			for i in range(self.tbl_parcelle.rowCount()):
				self.tbl_parcelle.showRow(i)
				
			self.button_box.setEnabled(True)	
		
		self.lst_saf_maj.blockSignals(False)
		self.lst_saf_origin.blockSignals(False)
		
	def chg_lst_saf_maj(self, index):
		self.lst_saf_maj.blockSignals(True)
		self.lst_saf_origin.blockSignals(True)
		
		if len(self.tbl_saf_maj)>0 and self.tbl_saf_maj[index] and index>-1:
			self.saf_maj.setText(str(self.tbl_saf_maj[index]))
		
			self.lst_saf_origin.setCurrentIndex(-1)	
			self.saf_origin.setText('N.P.')

			with conn:
				with conn.cursor() as cur:
					rq_parc_saf = """
					SELECT DISTINCT
						cad_site_id, cadastre_site.date_fin as date_fin_site, cadastre_cen.date_fin as date_fin_cen
					FROM			
						animation_fonciere.rel_eaf_foncier
						JOIN animation_fonciere.rel_saf_foncier USING (rel_eaf_foncier_id)
						JOIN foncier.cadastre_site USING (cad_site_id)
						JOIN cadastre.cadastre_cen USING (cad_cen_id)
					WHERE 
						lot_bloque = 'f' AND rel_saf_foncier.session_af_id = """+str(self.tbl_saf_maj[index])
					cur.execute(rq_parc_saf)
					res_parc_saf = cur.fetchall() 
					i = 0 #Déclaration à 0 d'une variable pour boucler sur toutes les options de la requête identifiée plus haut
					self.tbl_parc_saf = []
					self.prob_saf = 'NON'
					while i < len(res_parc_saf): #Boucle sur toutes les options
						if res_parc_saf[i][1] != 'N.D.' or res_parc_saf[i][2] != 'N.D.':
							self.prob_saf = 'OUI'
						else:
							id = res_parc_saf[i][0] #Déclaration de la variable stockant l'identifiant
							self.tbl_parc_saf.append(id)
						i+=1
						
			if self.prob_saf == 'OUI':
				QMessageBox.critical(None, "Attention", "Cette session comporte des alertes et doit être mise à jour")
				self.lst_saf_origin.setCurrentIndex(-1)	
				self.saf_origin.setText('N.P.')
				self.lst_saf_maj.setCurrentIndex(-1)	
				self.saf_maj.setText('N.P.')
				self.button_box.setEnabled(False)
			else :
				for r in range(self.tbl_parcelle.rowCount()):
					new_lot = 'NON'
					for cad_site_id in self.tbl_parcelle.item(r, 2).text().split(','):
						if cad_site_id not in self.tbl_parc_saf:
							new_lot = 'OUI'
					if new_lot == 'NON':
						self.tbl_parcelle.hideRow(r)
					else:
						self.tbl_parcelle.showRow(r)
				
				self.button_box.setEnabled(True)
		
		self.lst_saf_maj.blockSignals(False)
		self.lst_saf_origin.blockSignals(False)
		
		