# MailCheckboxPlugin

from trac.core import *
from trac.perm import IPermissionRequestor
from trac.web.chrome import ITemplateProvider, Chrome, add_stylesheet
from trac.web.api import ITemplateStreamFilter
from trac.web.main import IRequestFilter
from genshi.filters.transform import Transformer
from trac.ticket.web_ui import TicketModule

class MailCheckboxModule(Component):
    implements(ITemplateProvider, IRequestFilter, ITemplateStreamFilter)

    always_notify_updater = None
    always_notify_owner = None
    always_notify_reporter = None

    checkbox_notify_updater = None
    checkbox_notify_owner = None
    checkbox_notify_reporter = None

    # ITemplateProvider methods
    def get_htdocs_dirs(self):
        return []

    def get_templates_dirs(self):
        from pkg_resources import resource_filename
        return [resource_filename(__name__, 'templates')]

    # ITemplateStreamFilter methods
    def filter_stream(self, req, method, filename, stream, formdata):
        """Adds MailCheckbox form to the ticket page"""
        if filename == 'ticket.html':
            return stream | Transformer('//div[@class="buttons"]'). \
                                before(self._generate_form(req, formdata) )
        return stream

    # IRequestFilter methods
    def pre_process_request(self, req, handler):
        """Look for TicketHandler posts and hack them"""
        if isinstance(handler, TicketModule) and req.method == 'POST':
            always_notify_updater = self.config.getbool('notification','always_notify_updater')
            checkbox_notify_updater = (req.args.get('checkbox_notify_updater') != None)
            if always_notify_updater != checkbox_notify_updater:
                self.always_notify_updater = always_notify_updater
                self.checkbox_notify_updater = checkbox_notify_updater
                self.config.set('notification', 'always_notify_updater', checkbox_notify_updater)
                self.env.log.debug("CONFIG.NOTIFICATION.ALWAYS_NOTIFY_UPDATER changed")

            always_notify_owner = self.config.getbool('notification','always_notify_owner')
            checkbox_notify_owner = (req.args.get('checkbox_notify_owner') != None)
            if always_notify_owner != checkbox_notify_owner:
                self.always_notify_owner = always_notify_owner
                self.checkbox_notify_owner = checkbox_notify_owner
                self.config.set('notification', 'always_notify_owner', checkbox_notify_owner)
                self.env.log.debug("CONFIG.NOTIFICATION.ALWAYS_NOTIFY_owner changed")

            always_notify_reporter = self.config.getbool('notification','always_notify_reporter')
            checkbox_notify_reporter = (req.args.get('checkbox_notify_reporter') != None)
            if always_notify_reporter != checkbox_notify_reporter:
                self.always_notify_reporter = always_notify_reporter
                self.checkbox_notify_reporter = checkbox_notify_reporter
                self.config.set('notification', 'always_notify_reporter', checkbox_notify_reporter)
                self.env.log.debug("CONFIG.NOTIFICATION.ALWAYS_NOTIFY_reporter changed")

            # TODO: cc recipients are from ticket data in database, so it can not be overwritten
            # if req.args.get('checkbox_notify_cc'):

        return handler

    def post_process_request(self, req, template, content_type):
        """No-op"""
        return (template, content_type)

    def post_process_request(self, req, template, data, content_type):
        """rollback"""
        if self.always_notify_updater != None:
            self.config.set('notification', 'always_notify_updater', self.always_notify_updater)
            self.config.save
            self.always_notify_updater = None
            self.env.log.debug("CONFIG.NOTIFICATION.ALWAYS_NOTIFY_UPDATER rollback")
        if self.always_notify_owner != None:
            self.config.set('notification', 'always_notify_owner', self.always_notify_owner)
            self.config.save
            self.always_notify_owner = None
            self.env.log.debug("CONFIG.NOTIFICATION.ALWAYS_NOTIFY_OWNER rollback")
        if self.always_notify_reporter != None:
            self.config.set('notification', 'always_notify_reporter', self.always_notify_reporter)
            self.config.save
            self.always_notify_reporter = None
            self.env.log.debug("CONFIG.NOTIFICATION.ALWAYS_NOTIFY_REPORTER rollback")
        # TODO:
        # if self.cc_recipients != None:

        return (template, data, content_type)

    # internal methods
    def _generate_form(self, req, data):
        formdata = dict(data)

        # checkbox disabled?
        smtp_disabled = True
        if self.config.getbool('notification','smtp_enabled'):
            smtp_disabled = None

        # checkbox checked?
        always_notify_updater = None
        if smtp_disabled == None and (
            self.checkbox_notify_updater or (
                self.checkbox_notify_updater == None and
                self.config.getbool('notification', 'always_notify_updater'))):
            always_notify_updater = True
            self.env.log.debug("always_notify_updater is true")
        self.checkbox_notify_updater = None

        always_notify_owner = None
        if smtp_disabled == None and (
            self.checkbox_notify_owner or (
                self.checkbox_notify_owner == None and
                self.config.getbool('notification', 'always_notify_owner'))):
            always_notify_owner = True
            self.env.log.debug("always_notify_owner is true")
        self.checkbox_notify_owner = None

        always_notify_reporter = None
        if smtp_disabled == None and (
            self.checkbox_notify_reporter or (
                self.checkbox_notify_reporter == None and
                self.config.getbool('notification', 'always_notify_reporter'))):
            always_notify_reporter = True
            self.env.log.debug("always_notify_reporter is true")
        self.checkbox_notify_reporter = None

        always_notify_cc = None
        if smtp_disabled == None:
            always_notify_cc = True

        formdata['smtp_disabled'] = smtp_disabled
        formdata['always_notify_updater'] = always_notify_updater
        formdata['always_notify_owner'] = always_notify_owner
        formdata['always_notify_reporter'] = always_notify_reporter
        formdata['always_notify_cc'] = always_notify_cc

        stream = Chrome(self.env).render_template(req, 'mailcheckbox.html',
              formdata, fragment=True)
        return stream.select('//fieldset[@id="mailcheckbox"]')
