# -*- coding: utf-8 -*-
# WikiLinkMaker 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 pkg_resources import resource_filename


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

    # ITemplateProvider methods

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

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

    # IRequestHandler methods

    def match_request(self, req):
        return re.match(r'^/WikiLinkMaker(?:/(.*)|/wiki|/repository)', req.path_info) is not None

    def process_request(self, req):

        if re.match(r'^/WikiLinkMaker/wikilinkmaker.js',req.path_info) :
            return 'wikilinkmaker.js',{},'text/plain'

        current = req.args.get('dir') or ""
        if current and not current.endswith("/"):
            current += "/"

        result = ""
        if re.match(r'/WikiLinkMaker/wiki' , req.path_info) :
            result = self.process_wiki( req,current)

        if re.match(r'/WikiLinkMaker/repository' , req.path_info ):
            result = self.process_repository( req , current)

        req.send_response(200)
        req.send_header('Content-Type', 'text/html')
        req.end_headers()
        req.write(result)

    def process_repository(self ,req ,current):
        repo = self.env.get_repository(req.authname)
        node = repo.get_node(current)
        if node.isfile:
            return '<ul class="jqueryFileTree" style="display: none;"></ul>'

        nodes = node.get_entries()
        if not nodes :
            return '<ul class="jqueryFileTree" style="display: none;"></ul>'

        childlen = []
        for c in nodes:
            childlen.append(c)

        childlen.sort( cmp=lambda x, y: cmp(x.name, y.name) )

        result = '<ul class="jqueryFileTree" style="display: none;">'
        for child in childlen:
            if child.isdir:
                result += '    <li class="directory collapsed"><a href="#" rel="%s/">%s</a></li>' % ( child.path, child.name)

        for child in childlen:
            if child.isfile:
                ext = child.name.split(".")[-1]
                result += '    <li class="file ext_%s"><a href="#" rel="%s">%s</a></li>' % ( ext ,child.path , child.name)

        result += "</ul>"

        return result


        
    def process_wiki(self ,req , current):

        db = self.env.get_db_cnx()
        cursor = db.cursor()
        
        sqlcommand = """
SELECT name,MAX(time)
  FROM wiki WHERE name LIKE  '%s%%'
 GROUP BY name
 ORDER BY name ASC
"""
        sqlcommand = sqlcommand % (current)
        cursor.execute ( sqlcommand )

        rows = [ name[len(current) :] for n,[name,time] in enumerate(cursor) ]

        dirs = []
        files = []

        for name in rows:
            path = name.split("/")
            if len(path) > 1 :

                d = ("%s%s/" % (current ,path[0]) , path[0])
                if d not in dirs :
                    dirs.append(d)
 
            else:
                files.append(("%s%s" % (current ,name),name))

        result = '<ul class="jqueryFileTree" style="display: none;">'
        
        for path , name in dirs :
            result += '    <li class="directory collapsed"><a href="#" rel="%s">%s</a></li>' % ( path , name)
        
        for path , name in files:
            result += '    <li class="file ext_txt"><a href="#" rel="%s">%s</a></li>' % ( path , name)
        
        result += "</ul>"
        
        return result

    # IRequestFilter methods
    
    def post_process_request(self, req, template, data, content_type):
        path = req.path_info
        
        def uses_wikilinkmaker(req):
            if re.match(r'/wiki/', req.path_info) :
                if req.method=='POST' :
                    return True
            if req.method=='GET' and req.args.get('action') == "edit" :
                return True
            if re.match(r'/ticket/[0-9]+', req.path_info) :
                return True
            if re.match(r'/newticket', req.path_info) :
                return True
                
        if uses_wikilinkmaker(req) :
            add_script(req, '/WikiLinkMaker/wikilinkmaker.js')
            add_script(req, 'wikilinkmaker/jquery.floatbox.js')
            add_script(req, 'wikilinkmaker/jqueryFileTree.js')

            add_stylesheet(req,'wikilinkmaker/wikilinkmaker.css')
            add_stylesheet(req,'wikilinkmaker/jqueryFileTree.css')

        return template, data, content_type

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

