# -*- 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, content_type):
        path = req.path_info
        
        def uses_newwikipagebutton(req):
            if template == 'wiki.cs' :
                return True
            return False
                
        if uses_newwikipagebutton(req) :
            req.hdf['newwikipagebutton.href.htdocs'] = req.href.chrome('newwikipagebutton')
            add_script(req, 'newwikipagebutton/jquery.js')
            add_script(req, 'newwikipagebutton/newwikipagebutton.js')

        return template, content_type

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

