# -*- coding: utf-8 -*-
# NewWikiPageButton plugin
import re 
 
from trac.core import *
from trac.web.chrome import ITemplateProvider, add_stylesheet, add_script
from trac.web.api import IRequestFilter, IRequestHandler
from trac.util import escape, Markup
from trac.perm import IPermissionRequestor

from pkg_resources import resource_filename


class NewWikiPageButtonPlugin(Component):
    implements( IRequestHandler ,ITemplateProvider ,IRequestFilter)

    # ITemplateProvider methods

    def get_templates_dirs(self):
        yield resource_filename(__name__, 'templates')

    def get_htdocs_dirs(self):
        yield 'newwikipagebutton', resource_filename(__name__, 'htdocs')
        

    # IRequestHandler methods

    def match_request(self, req):
        return re.match(r'^/NewWikiPageButton/newwikipagebutton.js', req.path_info) is not None

    def process_request(self, req):

        if re.match(r'^/NewWikiPageButton/newwikipagebutton.js',req.path_info) :
            if 'WIKI_CREATE' in req.perm('wiki') or 'WIKI_ADMIN' in req.perm('wiki'):

                return 'newwikipagebutton.js',{},'text/plain'


    # IRequestFilter methods
    
    def post_process_request(self, req, template, data, content_type):
        path = req.path_info
        
        def uses_newwikipagebutton(req):
            if template == 'wiki_view.html' :
                return True
            return False
                
        if uses_newwikipagebutton(req) :
            if 'WIKI_CREATE' in req.perm('wiki') or 'WIKI_ADMIN' in req.perm('wiki'):
                add_script(req, '/NewWikiPageButton/newwikipagebutton.js')

        return template, data, content_type

    def pre_process_request(self, req, handler):
        return handler

