# -*- coding: utf-8 -*-
"""
/***************************************************************************
 ParcelleToSiteDialog
								 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.								   *
 *																		 *
 ***************************************************************************/
"""

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
from functools import partial 
import datetime
from time import gmtime, strftime

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

class ParcelleToSiteDialog(QDialog, FORM_CLASS):
	def __init__(self, parent=None):
		"""Constructor."""
		super(ParcelleToSiteDialog, self).__init__(parent)
		QDialog.__init__(self)
		self.setupUi(self)
	
	def InitFormulaire(self, tbl_par_id, acces, host, port, bdd, user, mdp):
		self.lst_sites.currentIndexChanged.connect(self.change_lst_site)
					
		self.site_sel.setVisible(0)
		self.button_box.setEnabled(False)		
		conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
		cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
		self.lst_sites.clear() #Vidage de la combobox
		self.lst_pci.clear() #Vidage de la combobox
		
		this_year = strftime("%Y", gmtime())
		
		global tbl_lst_sites
		self.tbl_lst_sites = []
		rq_lst_sites = """
		SELECT DISTINCT site_id, site_nom 
		FROM sites.sites 
		WHERE site_id = 'PCEN'
		UNION
		SELECT DISTINCT site_id, site_nom 
		FROM 
			sites.sites 
			JOIN cadastre.parcelles ON (st_intersects(st_buffer(sites.geom_ecolo, 500), parcelles.geom))
		WHERE par_id IN("""
		for par_id in tbl_par_id :
			rq_lst_sites += """'"""+par_id + """',"""
		rq_lst_sites += """'123') ORDER BY site_id"""						
		with conn:
			with conn.cursor() as cur:
				cur.execute(rq_lst_sites)
				res_lst_sites = cur.fetchall() #requête de récupération des options possible de niveau 2 à partir du niveau 1 sélectionné
		
				if len(res_lst_sites) > 0:
					self.lst_sites.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_sites): #Boucle sur toutes les options de niveau 2
						self.tbl_lst_sites.append(str(res_lst_sites[i][0]))
						self.lst_sites.addItem(str(res_lst_sites[i][0]) + """ """ + str(res_lst_sites[i][1])) #Ajout à la combobox de l'option en cours de bouclage
						i=i+1 #implémentation de la variable permettant de suivre le bon index de la combobox
					self.lst_sites.setCurrentIndex(0)
					self.button_box.setEnabled(True)
				else :
					self.lst_sites.setVisible(0)
		
		self.lst_pci.addItem(str(int(this_year) - 4))
		self.lst_pci.addItem(str(int(this_year) - 3))
		self.lst_pci.addItem(str(int(this_year) - 2))
		self.lst_pci.addItem(str(int(this_year) - 1))
		self.lst_pci.addItem(str(int(this_year)))
		self.lst_pci.setCurrentIndex(4)
	
	def change_lst_site(self, index):
		if self.lst_sites.currentIndex() != -1:
			self.site_sel.setText(str(self.tbl_lst_sites[index]))
		else:
			self.button_box.setEnabled(False)