#!/usr/bin/env python
# -*- coding: utf-8 -*-
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 trac.wiki.formatter import wiki_to_html
from pkg_resources import resource_filename

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

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

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

    # IRequestHandler methods
    def match_request(self, req):
        return re.match(r'^/WikiPreviewOverray(?:(.*))', req.path_info) is not None


    def process_request(self, req):
        if re.match(r'^/WikiPreviewOverray/wikipreviewoverray.js',req.path_info) :
            if 'WIKI_CREATE' in req.perm('wiki') or 'WIKI_ADMIN' in req.perm('wiki'):
                return 'wikipreviewoverray.js',{},'text/plain'

    # IRequestFilter methods
    def post_process_request(self, req, template, data, content_type) :
        if re.match(r'/wiki/', req.path_info) and req.method =='GET' and req.args.get('action') == "edit" :
            add_script(req, '/WikiPreviewOverray/wikipreviewoverray.js')
        if not re.match(r'^wikipreviewoverray/wikipreviewoverray.css',req.path_info) :
            add_stylesheet(req, 'wikipreviewoverray/wikipreviewoverray.css')

        if re.match(r'^/WikiPreviewOverray/post',req.path_info) :
            if req.method == 'POST' :
                text = req.args.get('tohtml')
                html = unicode(wiki_to_html(text, self.env, req, absurls=1))
                
                req.send_response(200)
                req.send_header('Content-Type', 'applicatiion/x-www-form-urlencoded')
                req.end_headers()
                req.write(html)

        return template, data, content_type

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