# -*- coding: utf-8 -*-

import re

from trac.core import *
from trac.web.api import IRequestHandler

from renderer import ReportRenderer

class ReportIncludeModule(Component):
    
    implements(IRequestHandler)
    
    # IRequestHandler methods
    def match_request(self, req):
        match = re.match(r'^/tracreportinclude(?:/(.*))?', req.path_info)
        if match:
            return True
        else:
            return False

    def process_request(self, req):
        req.perm.assert_permission('REPORT_VIEW')
        
        try:
            index, content = self._parse_args(req.args)
        except KeyError:
            return 'reportinclude_response.html', {'response':''}, None
            
        req._reportinclude = index
        
        renderer = ReportRenderer(self.env)
        report = renderer.render(req, content)
        
        data = {'response': report.generate()}
        
        return 'reportinclude_response.html', data, None
    
    def _parse_args(self, args):
        return (int(args['index']), args['params'].replace('__AND__', '&'))
        