# -*- coding: utf-8 -*-
import pkg_resources
import re

from trac.core import *

try:
    from trac.web.main import IRequestHandler
except:
    from trac.web import IRequestHandler

from trac.wiki.model import WikiPage
from trac.mimeview.api import Context
from trac.web.chrome import  add_stylesheet,ITemplateProvider


class WlWriter(Component):
    implements(IRequestHandler,ITemplateProvider)    

    # ITemplateProvider methods
    def get_htdocs_dirs(self):
        return [('tracblogrpc',pkg_resources.resource_filename(__name__, 'htdocs'))]

    def get_templates_dirs(self):
        return [pkg_resources.resource_filename(__name__, 'templates')]

    
    # IRequestHandler methods
    def match_request(self, req):
        match = re.match(r'^/wlwriter(?:/(.*))?', req.path_info)
        if match:
            if match.group(1):
                req.args['action'] = match.group(1)
            return 1
        if req.path_info == r'wlwmanifest.xml':
            req.args['action'] = 'wlwmanifest.xml'
            return 1

    def process_request(self, req):
        action = req.args.get('action', '')
        if action == 'WebLayout':
            data = {}
            add_stylesheet(req, 'common/css/wiki.css')
            add_stylesheet(req, 'tracblogrpc/css/wiki_temp_view.css')
            return "WebLayout.html",data,None

        elif action == 'WebPreview':
            pagename = 'WikiStart'      
            #page = WikiPage(self.env, pagename)
            #context = Context(self.env, req)('wiki', pagename)
            context = Context.from_request(req,'wiki',pagename)
            add_stylesheet(req, 'common/css/wiki.css')
            add_stylesheet(req, 'tracblogrpc/css/wiki_temp_view.css')
            #context.resource.text = '{post-body}'
            data = {'page': context.resource,
                    'context': context,
                    'action': 'view',
                    'page_name': '{post-title}',
                    #'attachments': AttachmentModule(self.env).attachment_list(context),
                    'title': 'WebPreview'}
            return "WebPreview.html",data,None

        elif action == 'wlwmanifest.xml':
            data = {}
            req.send_header('Content-Type', 'application/xml')
            return "wlwManifest.xml",data,None
        #if action == '':
        elif action == 'LiveClipboard':
            data = {}
            add_stylesheet(req, 'tracblogrpc/css/wiki_temp_view.css')
            return "liveClipboardCatarog.html",data,None
        else:
            pagename = self.lastpage(req)
            return req.redirect(req.href.wiki(pagename))

            self.log.debug('wlwRecentPost(%s)' %(req.href.wiki(pagename),))
    
            add_stylesheet(req, 'common/css/wiki.css')
            add_stylesheet(req, 'tracblogrpc/css/wiki_temp_view.css')
            page = WikiPage(self.env, pagename)
            context = Context(self.env, req)('wiki', pagename, 
                                             resource=page)
            req.perm.require('WIKI_VIEW', context)
            (t1,t2,t3) = self._render_view(context)
    
            return "wiki_temp_view.html",t2,t3
        


        
    def lastpage(self,req):
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        #cursor.execute('SELECT name,author FROM wiki '
        #               'WHERE author=%s ORDER BY time DESC',(get_reporter_id(req, 'author'),))
        cursor.execute('SELECT name,author FROM wiki '
                       'ORDER BY time DESC Limit 1')
        rownum = 0
        row = cursor.fetchone()
        if row:
            name,author = row
            return name
        return None

