# -*- coding: utf-8 -*-
"""
/***************************************************************************
 ParcelleToActeDialog
								 A QGIS plugin
 Permet d'associer des parcelles à des actes
							 -------------------
		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.								   *
 *																		 *
 ***************************************************************************/
"""

import os
import psycopg2 
import psycopg2.extras
import base64
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 gmtime, strftime

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

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

class ParcelleToActeDialog(QDialog, FORM_CLASS):
	def __init__(self, parent=None):
		"""Constructor."""
		global host
		host = bd_cen_host
		global port
		port = bd_cen_port
		global bdd
		bdd = bd_cen_name
		
		super(ParcelleToActeDialog, self).__init__(parent)
		QDialog.__init__(self)
		# Set up the user interface from Designer.
		# After setupUI you can access any designer object by doing
		# self.<objectname>, and you can use autoconnect slots - see
		# http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
		# #widgets-and-dialogs-with-auto-connect
		self.setupUi(self)
	
	def InitFormulaire(self, site_id, acces, user, mdp):		
		self.chk_convention.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))
		self.chk_acquisition.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))
		self.flt_date_today.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))
		self.flt_date_week.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))
		self.flt_date_month.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))
		self.flt_date_unknown.clicked.connect(partial(self.InitFormulaire, site_id = site_id, acces='reload', user = user, mdp = mdp))		
		self.lst_actes.blockSignals(True)
		self.lst_motif_maj.blockSignals(True)
		if acces == 'load':
			self.chk_convention.setChecked(1)
			self.chk_acquisition.setChecked(1)
			self.flt_date_unknown.setChecked(1)
			
		self.no_acte.setVisible(0)
		self.type_acte_sel.setVisible(0)
		self.motif_maj_id.setVisible(0)
		self.cal_date_modif.setVisible(0)
		self.motif_maj_id.setText('');
		self.button_box.setEnabled(False)
		self.date_modif.setText('N.P.')
		global conn, cur
		conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
		cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
		self.lst_actes.clear() #Vidage de la combobox
		self.lst_motif_maj.clear() #Vidage de la combobox
		k = 0
		aujourdhui = strftime("%Y-%m-%d", gmtime())
		this_week = strftime("%U", gmtime())
		tbl_site_id = site_id
		self.no_acte.setVisible(1)
		self.lst_actes.setVisible(0)
		self.lst_motif_maj.setVisible(0)
		global tbl_typemfu
		tbl_typemfu = []
		global tbl_motif_maj
		tbl_motif_maj = []	
		rq_lst_motif = """
		SELECT motif_maj_id as id, motif_maj_lib as lib 
		FROM 
			foncier.d_motif_maj
		WHERE motif_maj_id != 2 AND motif_maj_manip IN ('entree', 'entree/sortie')
		ORDER BY motif_maj_ordre"""
		if self.chk_convention.isChecked() == 0:
			rq_lst_motif = rq_lst_motif + " AND motif_maj_acte NOT LIKE '%Convention%'"		
		if self.chk_acquisition.isChecked() == 0:
			rq_lst_motif = rq_lst_motif + " AND motif_maj_acte NOT LIKE '%Acquisition%'"
		with conn:
			with conn.cursor() as cur:
				cur.execute(rq_lst_motif)
				global res_lst_motif
				res_lst_motif = cur.fetchall() #requête de récupération des options possible de niveau 2 à partir du niveau 1 sélectionné
				if len(res_lst_motif) > 0:
					self.lst_motif_maj.setVisible(1)				
					i = 0 #Déclaration à 0 d'une variable pour boucler sur toutes les options de la requête identifiée précédement
					while i < len(res_lst_motif): #Boucle sur toutes les options de niveau 2
						lib = res_lst_motif[i][1] #Déclaration de la variable stockant le libellé complet de la requête
						self.lst_motif_maj.addItem(lib) #Ajout à la combobox de l'option en cours de bouclage
						tbl_motif_maj.append(res_lst_motif[i][0])
						i=i+1 #implémentation de la variable permettant de suivre le bon index de la combobox
					self.lst_motif_maj.setCurrentIndex(-1)		
		
		while k < len(tbl_site_id):
			cur_site_id = tbl_site_id[k]
			k = k + 1						
			rq_lst_mfu = """
			WITH tprob AS (
				SELECT DISTINCT acte AS acte_id FROM alertes.v_prob_mfu_baddata
				UNION
				SELECT DISTINCT mfu_id AS acte_id FROM alertes.v_prob_cadastre_cen WHERE statutmfu_id = 1
				UNION
				SELECT DISTINCT acte AS acte_id FROM alertes.v_alertes_mu WHERE alerte LIKE 'termin%'
				UNION
				SELECT DISTINCT mfu_id AS acte_id FROM alertes.v_prob_mfu_sansparc
			),
			t1 AS (
				SELECT DISTINCT
					acte as type_acte, mfu_id as acte_id, mf_acquisitions.mf_lib as acte_lib, typmfu_lib as acte_typ, 
					v_tdb_mfu.date_sign_acte as acte_date, mf_acquisitions.maj_date as maj_date
				FROM 
					alertes.v_tdb_mfu
					JOIN foncier.mf_acquisitions ON (mf_id = mfu_id)
					LEFT JOIN tprob ON (acte_id = mfu_id)
				WHERE statutmfu_id IN (0, 1) AND tbl_site_id ILIKE '%"""+cur_site_id+"""%' AND tprob.acte_id IS NULL
				UNION 
				SELECT DISTINCT
					acte as type_acte, mfu_id as acte_id, mu_conventions.mu_lib as acte_lib, typmfu_lib as acte_typ, 
					v_tdb_mfu.date_effet_conv as acte_date, mu_conventions.maj_date as maj_date
				FROM 
					alertes.v_tdb_mfu
					JOIN foncier.mu_conventions ON (mu_id = mfu_id)
					LEFT JOIN tprob ON (acte_id = mfu_id)
				WHERE statutmfu_id IN (0, 1) AND tbl_site_id ILIKE '%"""+cur_site_id+"""%' AND tprob.acte_id IS NULL
			)
			SELECT * FROM t1 WHERE 1=1"""
			
			if self.chk_convention.isChecked() == 0:
				rq_lst_mfu = rq_lst_mfu + " AND type_acte != 'Convention'"
			
			if self.chk_acquisition.isChecked() == 0:
				rq_lst_mfu = rq_lst_mfu + " AND type_acte != 'Acquisition'"
				
			if self.flt_date_today.isChecked() == 1:
				rq_lst_mfu = rq_lst_mfu + " AND LEFT(maj_date, 10) = '"+aujourdhui+"'"
			elif self.flt_date_week.isChecked() == 1:
				rq_lst_mfu = rq_lst_mfu + " AND EXTRACT(WEEK FROM to_date(maj_date, 'YYYY-MM-DD')) = " + this_week
			elif self.flt_date_month.isChecked() == 1:
				rq_lst_mfu = rq_lst_mfu + " AND TO_DATE(maj_date, 'YYYY-MM-DD') BETWEEN TO_DATE('"+strftime("%Y-%m", gmtime())+"-01', '%Y-%m-%d') AND TO_DATE('"+strftime("%Y-%m-%d", gmtime())+"', 'YYYY-MM-DD')"
			with conn:
				with conn.cursor() as cur:
					cur.execute(rq_lst_mfu)			
					res_lst_mfu = cur.fetchall() #requête de récupération des options possible de niveau 2 à partir du niveau 1 sélectionné								
					if len(res_lst_mfu) > 0:
						self.no_acte.setVisible(0)
						self.lst_actes.setVisible(1)				
						i = 0 #Déclaration à 0 d'une variable pour boucler sur toutes les options de la requête identifiée précédement
						while i < len(res_lst_mfu): #Boucle sur toutes les options de niveau 2
							lib = res_lst_mfu[i][1] #Déclaration de la variable stockant le libellé complet de la requête
							self.lst_actes.addItem(lib) #Ajout à la combobox de l'option en cours de bouclage
							tbl_typemfu.append(res_lst_mfu[i][0])
							i=i+1 #implémentation de la variable permettant de suivre le bon index de la combobox
						self.lst_actes.setCurrentIndex(-1)			
		
		self.lst_actes.currentIndexChanged.connect(self.change_lst_acte)
		self.lst_actes.blockSignals(False)
		self.lst_motif_maj.currentIndexChanged.connect(self.change_lst_motif_maj)
		self.lst_motif_maj.blockSignals(False)
	
	def change_lst_acte(self, index):
		self.lst_motif_maj.blockSignals(True)
		if self.lst_actes.currentIndex() != -1 and self.date_modif.text() != 'N.P.' and self.lst_motif_maj.currentIndex() != -1 :
			self.button_box.setEnabled(True)
		else:
			self.button_box.setEnabled(False)
		if index != -1 and tbl_typemfu[index] == 'Acquisition':
			self.type_acte_sel.setText('r_cad_site_mf')
		elif index != -1 and tbl_typemfu[index] == 'Convention':
			self.type_acte_sel.setText('r_cad_site_mu')
			
		with conn:
			with conn.cursor() as cur:
				if self.motif_maj_id.text() != '':
					rq_check_lst_motif = "SELECT motif_maj_id as id, motif_maj_lib as lib FROM foncier.d_motif_maj WHERE motif_maj_manip IN ('entree', 'entree/sortie') AND motif_maj_acte LIKE '%"+str(tbl_typemfu[index])+"%' AND motif_maj_id = "+str(self.motif_maj_id.text())
					cur.execute(rq_check_lst_motif)
					res_check_lst_motif = cur.fetchall()
					if len(res_check_lst_motif) == 0 :
						self.lst_motif_maj.setCurrentIndex(-1)
						self.motif_maj_id.setText('')
						
				rq_lst_motif = """
				SELECT motif_maj_id as id, motif_maj_lib as lib 
				FROM foncier.d_motif_maj 
				WHERE motif_maj_id != 2 AND motif_maj_manip IN ('entree', 'entree/sortie') AND motif_maj_acte LIKE '%"+str(tbl_typemfu[index])+"%'
				ORDER BY motif_maj_ordre"""
				cur.execute(rq_lst_motif)
				res_lst_motif = cur.fetchall() #requête de récupération des options possible de niveau 2 à partir du niveau 1 sélectionné
				if len(res_lst_motif) > 0:
					self.lst_motif_maj.setVisible(1)
					self.lst_motif_maj.clear()
					tbl_motif_maj.clear()
					i = 0 #Déclaration à 0 d'une variable pour boucler sur toutes les options de la requête identifiée précédement
					j = -1
					while i < len(res_lst_motif): #Boucle sur toutes les options de niveau 2
						lib = res_lst_motif[i][1] #Déclaration de la variable stockant le libellé complet de la requête
						self.lst_motif_maj.addItem(lib) #Ajout à la combobox de l'option en cours de bouclage
						tbl_motif_maj.append(res_lst_motif[i][0])
						if str(res_lst_motif[i][0]) == str(self.motif_maj_id.text()):
							j = i
						i=i+1 #implémentation de la variable permettant de suivre le bon index de la combobox
					self.lst_motif_maj.setCurrentIndex(j)
				self.lst_motif_maj.blockSignals(False)

	def change_lst_motif_maj(self, index):
		if self.lst_motif_maj.currentIndex() != -1:
			self.motif_maj_id.setText(str(tbl_motif_maj[index]))
		if self.lst_actes.currentIndex() != -1 and self.date_modif.text() != 'N.P.' and self.lst_motif_maj.currentIndex() != -1 :
			self.button_box.setEnabled(True)
		else:
			self.button_box.setEnabled(False)