# -*- coding: UTF-8 -*-
# -*- Mode: Python; py-indent-offset: 4 -*-
# Authors: Nik Kim <fafhrd@datacom.kz> 
__version__ = '$Revision: 1.1 $'[11:-2]

import traceback
from Globals import InitializeClass
from OFS.SimpleItem import SimpleItem
from OFS.PropertyManager import PropertyManager

from AccessControl import ClassSecurityInfo, Permissions

from Products.Event.EventPermissions import *
from Products.Event.EventService import EventService
from Products.Event.EventRegistry import EventRegistry, _registry as _xfaceregistry
from Products.PageTemplates.PageTemplateFile import PageTemplateFile

from email import message_from_string

from ISMTPEvents import ISMTPEvent
from SMTPEvents import SMTPEvent, SMTPDiscoveryEvent

_marker = ()

class SMTPService(EventService, PropertyManager):
    """ smtp service, all objects that wants
    recieve emails must subscribe here """
    __implements__ = EventService.__implements__

    id='smtp_server'
    title = 'SMTPService'

    security = ClassSecurityInfo()

    max_size = 0
    allowed_peers = ()
    
    _properties=(
        {'id': 'max_size', 'type': 'int', 'mode': 'w'},
        {'id': 'allowed_peers', 'type': 'lines', 'mode':'w'},
        )

    manage_options = (PropertyManager.manage_options +
                      EventService.manage_options)

    security.declareProtected(
        Permissions.view_management_screens, 'manage_viewSubscriptions')
    manage_viewSubscriptions = PageTemplateFile(
        'zpt/view_subscriptions',
        globals(),
        __name__='manage_viewSubscriptions'
        )
    
    def __init__(self, id='smtp_server'):
        """ """
        EventService.__init__(self)

    def process_message(self, peer, from_addr, to_addrs, data):
        """ """
        # need check peer
        if self.allowed_peers and (peer not in self.allowed_peers):
            # send error message
            return 'Peer not allowed'

        if self.max_size and (len(data) > self.max_size):
            # send error message
            return 'Max size exceeded'
        
        try:
            # i think this must be moved to Server
            message = message_from_string(data)
        except:
	    # send error message
            traceback.print_exc()

        subscriptions = [s for s, et, fl in self.listAllSubscriptions()
                         if et == ISMTPEvent]

        for to_addr in to_addrs:
            user, domain = to_addr.split('@', 1)
            found_recipient = 0

            event1 = SMTPEvent(self, from_addr, to_addr, message, user, domain)
            event2 = SMTPDiscoveryEvent(
                self, from_addr, to_addr, message, user, domain)
            
            for subscriber in subscriptions:
                try:
                    if subscriber.notify(event2):
                        found_recipient = 1
                        subscriber.notify(event1)
                except:
                    traceback.print_exc()
                    # fixme: send error message
            
            if not found_recipient:
                # send error message
                pass

    def manage_removeSubscriptions(self, no, REQUEST=None):
        """ """
        subs = self.listAllSubscriptions()

        remove_list = [subs[n] for n in [int(n) for n in no]]

        for subs, event, fl in remove_list:
            self.unsubscribe( subs, event_type=event )

        if REQUEST is not None:
            REQUEST.RESPONSE.redirect('manage_viewSubscriptions')
        
        
InitializeClass(SMTPService)
