# -*- coding: utf-8 -*-
"""
/***************************************************************************
 pluginsCenSavoie_v3
								 A QGIS plugin
 Load plugins of CEN Savoie
							  -------------------
		begin				: 2016-09-08
		git sha			    : $Format:%H$
		copyright			: (C) 2016 by CEN Savoie
		email				: sig@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 the PyQt and QGIS libraries
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from qgis.core import *

import webbrowser, os
import os.path, sys
import psycopg2 
import psycopg2.extras
import base64

# Set up current path.
currentPath = os.path.dirname( __file__ )

#Import own tools
from pluginsCenSavoie_v3.tools.create_sessionAF import CreateSessionAF
from pluginsCenSavoie_v3.tools.backinMFU import BackinMFU
from pluginsCenSavoie_v3.tools.parcelle_to_acte import ParcelleToActe
from pluginsCenSavoie_v3.tools.parcelle_to_site import ParcelleToSite
from pluginsCenSavoie_v3.tools.help import help
# 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

class pluginsCenSavoie_v3:
	def __init__(self, iface):
		self.iface = iface
		self.canvas = self.iface.mapCanvas() 
		self.plugin_dir = os.path.dirname(__file__)
		
		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
		
	def initGui(self):
		
		if sys.platform == 'linux':
			os_user = os.environ['USER']
		else:
			os_user = os.environ['USERNAME']
		self.toolBar = self.iface.addToolBar("pluginsCenSavoie_v3")
		self.toolBar.setObjectName("Plugins CEN Savoie")
		
		global user, mdp
		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()
		
		conn = psycopg2.connect("host=" + host + " port=" + port + " dbname=" + bdd + " user=" + user + " password=" + mdp)
		cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
		cur.execute("""
		WITH RECURSIVE t(oid) AS (
		VALUES ((SELECT oid FROM admin_sig.utilisateurs WHERE utilisateur_id = '""" + os_user + """' OR utilisateur_os = '""" + os_user + """'))
		UNION ALL
		SELECT grosysid
		FROM pg_catalog.pg_group JOIN t ON (t.oid = ANY (grolist))
		)
		SELECT DISTINCT groname
		FROM pg_catalog.pg_group JOIN t ON (t.oid = pg_group.grosysid)""")
		user_group = cur.fetchall()
		tbl_grp = []
		i = 0
		while i < len(user_group): #Boucle sur toutes les options
			tbl_grp.append(user_group[i][0])
			i=i+1
			
		cur.execute("""
		WITH RECURSIVE t(oid) AS (
			VALUES ((SELECT oid FROM admin_sig.utilisateurs WHERE utilisateur_id = '""" + os_user + """' OR utilisateur_os = '""" + os_user + """'))
			UNION ALL
			SELECT grosysid
			FROM pg_catalog.pg_group JOIN t ON (t.oid = ANY (grolist))
		),
		t_group AS (
			SELECT DISTINCT groname
			FROM pg_catalog.pg_group JOIN t ON (t.oid = pg_group.grosysid))

		SELECT 
            count(*) FILTER (WHERE grant_elt_id = 3 AND grant_group_droit = 't' AND grant_group_id IN (groname)) as parc,
            count(*) FILTER (WHERE grant_elt_id = 26 AND grant_group_droit = 't' AND grant_group_id IN (groname)) as site
		FROM foncier.grant_group JOIN t_group ON (groname = grant_group_id)""")
		can_parc_site = cur.fetchone()
			
		# # Get the tools	
		if 'cen_user' in tbl_grp:
			self.backinMFU = BackinMFU(self.iface,  self.toolBar)
			self.toolBar.addSeparator()
			self.toolBar.addSeparator()			
		if 'grp_foncier' in tbl_grp or 'grp_sig' in tbl_grp:			
			if can_parc_site[0] > 0:
				self.parcelle_to_acte = ParcelleToActe(self.iface,  self.toolBar)
			if can_parc_site[1] > 0:
				self.parcelle_to_site = ParcelleToSite(self.iface,  self.toolBar)
		if 'grp_animation_fonciere' in tbl_grp or 'grp_sig' in tbl_grp:
			self.create_sessionAF = CreateSessionAF(self.iface,  self.toolBar)
		if 'grp_animation_fonciere' in tbl_grp or 'grp_foncier' in tbl_grp or 'grp_sig' in tbl_grp:
			self.toolBar.addSeparator()
			self.toolBar.addSeparator()		
		if 'cen_user' in tbl_grp:
			self.help = help(self.iface,  self.toolBar)
		
		conn.close()
	
	def unload(self):
		del self.toolBar