#! /usr/bin/env python
#############################################################
#                                                           #
#   Author: Herve Menager                                   #
#   Organization:'Biological Software and Databases' Group, #
#                Institut Pasteur, Paris.                   #
#   Distributed under GPLv2 Licence. Please refer to the    #
#   COPYING.LIB document.                                   #
#                                                           #
#############################################################
import mb_cgi
import os 
import urllib2
import socket

def process(self):
    self.template_file = 'portal.html'
    if self.session:
        self.response['authenticated'] = self.session.isAuthenticated()
        self.response['activated'] = self.session.isActivated()
        actkey = self.request.getfirst('actkey')
        if actkey:
            self.response['actkey'] = actkey
    else:
        self.response['sessionId'] = None
        self.response['authenticated'] = False
        self.response['activated'] = False
    self.response['anonymousSession'] = (self.cfg.anonymousSession()!='no')
    self.response['authenticatedSession'] = (self.cfg.authenticatedSession()!='no')
    self.response['sessionLimit']='%.2f'%(float(self.cfg.sessionlimit())/1000)
    self.response['refresh_frequency']=self.cfg.refreshFrequency()
    #OPENID
    self.response['openid']=(self.cfg.openid()!=False)

    self.response['messages'] = []
    annFileName = os.path.normpath(os.path.join( self.cfg.portal_path(),"html/announcement.txt"))
    self.cssDir = '/'+self.cfg.portal_url(True)+"/css/"
    self.jsDir = '/'+self.cfg.portal_url(True)+"/js/"
    self.htDir = '/'+self.cfg.portal_url(True)+"/"
    welcome_url = None
    if self.cfg.welcome_config().get('format')=='atom':
        welcome_url =  self.cfg.cgi_url()+"/feed_view.py?url="+self.cfg.welcome_config().get('url')+"&amp;fmt="+self.cfg.welcome_config().get('format')
    elif self.cfg.welcome_config().get('format')=='html':
        welcome_url = self.cfg.welcome_config().get('url')
    if welcome_url:
        timeout = 1 # we set a reasonable timeout to avoid hanging on this problem before displaying the whole page.
        backup_timeout = socket.getdefaulttimeout()
        socket.setdefaulttimeout(timeout)
        try:
            self.welcome_html = unicode(''.join(urllib2.urlopen(welcome_url).readlines()), errors='ignore')
        except (urllib2.URLError ,urllib2.HTTPError), e:
            mb_cgi.c_log.error('error while loading welcome frame from %s' % welcome_url)
            # if we cannot get the custom page in time, we just pass
            pass
        socket.setdefaulttimeout(backup_timeout)
    if os.path.isfile(annFileName):
        templateCacheFile = open (annFileName,'r')
        self.response['announcement'] = templateCacheFile.read()
        templateCacheFile.close()
    # it is possible to ask for specific preloaded values in the form
    self.response['load']=[]
    for name in self.request.keys():
        if name.startswith("load::"):
            dict = name.split('::')
            service_name=dict[1]
            parameter_name=dict[2]
            value=self.request.getfirst(name)
            self.response['load'].append((service_name,parameter_name,value))


if __name__ == "__main__":
    mb_cgi.TALCGI(processFunction=process,useSession=True)
