# -*- coding: utf-8
# $Id$
#
# Copyright 2001, 2002 by IVA Team and contributors
#
# This file is part of IVA.
#
# IVA 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.
#
# IVA 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with IVA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
__version__ = "$Revision$"[11:-2]
import AccessControl
import OFS, Globals
from OFS import SimpleItem
import types
import time
from TraversableWrapper import Traversable
from Globals import Persistent
from AccessControl import ClassSecurityInfo, getSecurityManager, Unauthorized
from Cruft import Cruft
from common import translate, perm_edit, perm_view, mkTime
from Products.ZCatalog.CatalogPathAwareness import CatalogAware
from input_checks import strip_tags
from DateTime import DateTime
import calendar
calendar.setfirstweekday(0)
class KalendriSyndmus(
     OFS.SimpleItem.Item,
     Persistent,
     AccessControl.Role.RoleManager,
     Traversable,
     Cruft,
     CatalogAware
     ):
     """ Teade kalendris """
     meta_type = 'Event'
     security = ClassSecurityInfo()
     security.declareObjectPublic()
     
     def __init__(self, nimi, pikk='', algus=-1, lopp=-1, viide="", siseviide="", olek=0,blokerid=[]):
       "Alustus"
       if algus == -1:
	algus = time.time()
       if lopp == -1:
	lopp = time.time()
       self.nimi=nimi
       self.pikk=pikk
       self.algus=algus
       self.lopp=lopp
       self.viide=viide
       self.siseviide=siseviide
       self.blokerid = []
       self.olek=olek #0-ajatu sündmus 1-lõpetamata töö 2-lõpetatud töö
       self.icon_tag=None
       self.default_catalog = 'catalog_events'
     def manage_afterAdd(self, item, container):
	 """ index event """
	 self.index_object()
     def manage_beforeDelete(self, item, container):
	 """ unindex catalog """
	 self.unindex_object()
       
     security.declareProtected(perm_view,'getName')
     def getName(self):
	 """ Event name """
	 return self.nimi
     security.declareProtected(perm_view,'getIconTag')
     def getIconTag(self):
         if not hasattr(self,'icon_tag'):
		 self.icon_tag = None
         if self.icon_tag is not None:
             if self.icon_tag.endswith('odune'):
                 self.icon_tag += '.gif'
         if self.icon_tag is not None:
		 result = "
"
         else:
		 result = ""
         return result
     security.declareProtected(perm_view,'setIconTag')
     def setIconTag(self,path):
         self.icon_tag = path
         self.icon_tag = self.icon_tag
	 return self.icon_tag
       
     def getContent(self):
	 """ Event content """
	 return self.pikk
       
     security.declarePublic('kysiAlgus')
     def kysiAlgus(self):
       "Syndmuse algusaeg"
       return self.algus
     def kysiLopp(self):
       "Syndmuse lõppaeg"
       return self.lopp
     def get_start_time(self):
	 """ Event start time in DateTime format """
	 return DateTime(self.kysiAlgus()).ISO()
     def get_end_time(self):
	 """ Event end time in DateTime format """
	 return DateTime(self.kysiLopp()).ISO()
       
     def aegTekstina(self, REQUEST, aeg, timestamp=''):
       "tekstiesitus"
       if aeg==-1: return "*"
       if not timestamp:
	       timestamp = translate(self,'timestamp_format',default="%H:%M %Y-%m-%d",target=self.giveLanguage(REQUEST))
       else:
	       timestamp = REQUEST[timestamp]
       return time.strftime(timestamp, time.localtime(aeg))
     def tekstAjana(self, REQUEST, ajatekst):
       "Tagasi ajaformaati"
       return mktime(time.strptime(translate(self,'timestamp_format',default="%H:%M %Y-%m-%d",target=self.giveLanguage(REQUEST))), ajatekst)
     def kysiViide(self):
       "Välisviide"
       return self.viide
       
     def kysiSiseviide(self):
       "Siseviide"
       return self.siseviide
       
     def kysiSiseviiteURL(self):
       "Siseviide"
       return self.fle_root().absolute_url()+self.siseviide
       
     def siseviiteNimi(self):
       "Nagu funktsiooni nime ütleb"
       import re
       if self.siseviide=="": return ""
       m=self.siseviide.split("/")
       o=self.fle_root()
       try:
         for x in m:
           if len(x)>0:
            o=getattr(o, re.sub('%20',' ',x))
       except:
         return ""
       return o.get_name()
       
     def kysiSiseviiteLink(self):
	 "Koos"
	 return ""+self.siseviiteNimi()+""
       
     def kysiOlek(self):
       "Sündmuse olek"
       if hasattr(self, 'olek'): return self.olek
       return 0
     def getPersonalStatus(self,REQUEST):
	 """ """
	 if hasattr(self, 'status_'+str(REQUEST.AUTHENTICATED_USER)):
		 return getattr(self,'status_'+str(REQUEST.AUTHENTICATED_USER))
	 else:
		 return 0
	 return 0
       
     def olekuVarv(self, REQUEST):
       "Olekut illustreeriv lahter"
       if self.getPersonalStatus(REQUEST):
	       stat = self.getPersonalStatus(REQUEST)
       else:
	       stat = self.kysiOlek()
       if stat==0:
         return "\"black\""
       if stat==1: #pooleli
         if time.time()>self.lopp: #Hilinenud
           return "\"red\""
         else: return   "\"blue\""
       return  "\"green\""       
       
     def asukohaNimi(self):
       "Kursuse nimi, kus sündmus asub, muu sündmuse puhul None"
       aadress=self.absolute_url()
       algus=aadress.find('courses')
       if algus>=0:
         nr=aadress[algus:].split("/")[1]
         t=getattr(self.fle_root().courses, nr).get_name()
         m=aadress[algus:].split("/")
         for i in range(len(m)):
           if m[i]=="subgroups" and i+1