from Products.CPSMailAccess.mailbox import MailBoxView
from utils import getToolByName
from baseconnection import ConnectionError
from zLOG import LOG, DEBUG
try:
    from Products.zasyncdispatcher import asyncedCall, canAsync
    can_async = True
except ImportError:
    can_async = False
    
class PatchMailBoxView(MailBoxView):    
    def background_synchronisation(self, light=1,came_from=''):
        """ background synchronisation """
        mailbox = self.context
        box_name = mailbox.id
        req = self.request
        res = True 
        # looking for zasync
        if can_async and canAsync(self):
            # XXX need to get feedback in case of failures
            bckgrd = True
            root = portal_url.getPortalPath()
            root = root.replace('/', '.')
            if root[0] == '.':
                root = root[1:]
                try:
                    asyncedCall(self,
                        'python:home.%s.portal_webmail.%s.synchronize(light=%s)' \
                          % (root, box_name, str(light)))
                    fail_async = False
                except AttributeError:
                    fail_async = True
        else:
            fail_async = True

        if fail_async or not (can_async and canAsync(self)):
            bckgrd = False
            if not mailbox.isSynchronizing(1):
                try:
                    mailbox.synchronize(no_log=True, light=light)
                    psm = 'cpsma_synchronized'
                    res = True
                except ConnectionError, e:
                    psm = str(e)
                    mailbox.clearSynchro(1)
                    res = False
            else:
                psm = 'cps_already_synchronizing'

        portal_url = getToolByName(self, 'portal_url')
        prtool = getToolByName(self,'portal_cpsportlets')
        prtool.manage_clearCache() 
        if req is not None:
            root = portal_url()
            if res:
                if bckgrd:
                    psm = 'cps_synchronizing'

            if hasattr(mailbox, 'INBOX'):
                page = '%s/portal_webmail/%s/INBOX' %(root, box_name)
            else:
                page = '%s/portal_webmail/%s' %(root, box_name)
                
            if came_from!='':
                return req.response.redirect(came_from)
            elif psm is not None:                  
                return req.response.redirect('%s/view?msm=%s'  % (page, psm))
            else:
                return req.response.redirect('%s/view'  % page)
                           