# -*- coding: latin-1 -*-
""" 
   Copyright (C) 2005 PimenTech SARL (http://www.pimentech.net)

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with this library; see the file COPYING.LIB.  If not,
   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.  
"""

from Products.PimenTechLibCommon.set import *
from Products.PimenTechLibCommon.pgobject import *

from Globals import HTMLFile

class PgList(PgObject):
	"""
	PgList Object
	  
	"""

	__PgObject_init = PgObject.__init__

	meta_type = "PgList"

	manage_options = (PgObject.manage_options[0],) + (
		{'label':'View', 'action':'html_view_pglist'},
		) + PgObject.manage_options[2:]

	index_html = HTMLFile('dtml/edit_pglist', globals())
	html_view_tmp_list = HTMLFile('dtml/view_tmp_list', globals())
	html_view_list = HTMLFile('dtml/view_list', globals())
	html_view_pglist = HTMLFile('dtml/view_pglist', globals())
	
	conditions = None
	reference = None
	content_tablename = None
	tablename = None
	_saved = 0

	def __init__(self, id, connection_id, initialized_from = 'postgresql'):
		self.__PgObject_init(id, connection_id)
		self.uid = None

	def manage_afterAdd(self, id, container):
		" Zope method : automaticaly called when an instance is created. "
		
		self.message("PgList.manage_afterAdd(%s)" % self.id)
		self._list = PDictSet('list')
		self._tmp_list = PDictSet('tmp_list')
		
	def update(self, uid=None):
		" update from postgres "
		self.uid = self.uid or int(uid)
		if not self.uid:
			self.error("Update of a PgList without uid")
			return
		
		self._create_current_row()
		
		PgObject.update(self)

		if len(self._list):
			del self._list
			self._list = PDictSet('list')
		if len(self._tmp_list):
			del self._tmp_list
			self._tmp_list = PDictSet('tmp_list')
		
		list = self.fetch(self.update_query % self.uid)
		self.construct(list, self._list)
		self._saved = 1

	def synchronize(self):
		self.create_list()
		query = "DELETE FROM list_element WHERE ref_list = %s;\n" % self.uid
		for el in self._list.keys():
			query += "INSERT INTO list_element (ref_list, ref_object, codecrea) VALUES (%s, %s, 'PgList(synchronize)');\n" % (self.uid, el)
		self.message(query)
		self.exec_sql(query)

	def create_list(self):		
		" Add a new list in potsgres "
		pass
		
	def construct(self, list):
		" build the list "
		pass

	def _save(self, title, REQUEST):
		self._saved = 1
		self.synchronize()
		self.title = title
		self[self.tablename]['ztitle'] = self.title
		self.commit(REQUEST)
		self.reindex()
	
	def save(self, title, REQUEST):
		" permanently add the pglist "
		self._save(title, REQUEST)
		self.reset_tmp_list()
		return REQUEST.RESPONSE.redirect("index_html")

	def is_saved(self):
		" return save state "
		return self._saved

	def get_list(self, REQUEST=None):
		" return the list "
		return self._list.values()

	def get_tmp_list(self, REQUEST=None):
		" return the choise list "
		return self._tmp_list.values()

	def reset_tmp_list(self):
		del self._tmp_list
		self._tmp_list = PDictSet('tmp_list')

	def init_tmp_list(self, REQUEST):
		"""
		Fill the tmp_list with the search engine
		Must be over defined
		"""
		pass

	def delete_elements(self, REQUEST):
		" remove objects from the list "
		if not REQUEST.form.has_key('checkbox'):
			return None
		list = REQUEST.form['checkbox']
		for k in list.keys():
			del self._list[int(k)]
		# synchonize
		if self.is_saved():
			self._save(self.title, REQUEST)
		return REQUEST.RESPONSE.redirect("%s?delete=ok " % self.getId())
			
	def add_elements(self, REQUEST):
		" add objects to the result list "
		if not REQUEST.form.has_key('checkbox'):
			return None
		list = REQUEST.form['checkbox']
		for k in list.keys():
			object_id = self._tmp_list[int(k)]
			if object_id != None:
				self._list.insert(object_id)

		# synchonize
		if self.is_saved():
			self._save(self.title, REQUEST)

		return REQUEST.RESPONSE.redirect("%s?add=ok " % self.getId())
	
	def _delete_element_everywhere(self, uid):
		self.message('delete element from lists')
		uid = int(uid)
		query = "DELETE FROM list_element WHERE ref_list = %s AND ref_object=%s" % (self.uid, uid)
		self.exec_sql(query)
		if self._list.has_key(uid):
			del self._list[uid]
		if self._tmp_list.has_key(uid):
			del self._tmp_list[uid]
	
	def delete_me(self, REQUEST):
		"Delete this object and its rows"
		self.warning('[pglist.py(delete_me)] delete pglist %s in %s named %s' % (
			self.getId(), self.aq_parent.meta_type, self.aq_parent.getId()))
		
		row = self[self.tablename]
		row['ref_statut'] = 1
		self.commit(REQUEST)
		
		query = ""
		for el in self._list.keys():	
			query += "UPDATE list_element SET codemodif='pglist.py[delete_me]', ref_statut=1 WHERE uid=%s;\n" % el
		self.message(query)
		self.fetch(query)
		
		self.aq_parent._delObject(self.getId())
		return REQUEST.RESPONSE.redirect('.')

class MiniRow(DictMap):
	"""
	You can use this object to fill a PgList
	"""

	meta_type = 'MiniRow'

	def __init__(self, uid, fields_dict):
		self.id = str(uid)
		DictMap.__init__(self, self.id)

		for k, v in fields_dict.items():
			self[k] = v

	
class MicroRow:
	"""
	Smallest object you can put in a PgList
	"""
	def __init__(self, k, v):
		self._k = k
		self._v = v
		self.id = str(k)
		
	def __hash__(self):
		return int(self._k)
	
	def key(self):
		return self._k
	
	def value(self):
		return self._v
	
	def __getitem__(self, k):
		return self._k
	
	def __repr__(self):
		return self.id
	
	def __str__(self):
		return self.id

	def __cmp__(self, other):
		return cmp(self.id, str(other))

