"""
See app/README.rst for setup instructions
"""

import cgi
import os

import django.conf
import django.template.loader

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

# --- docedit import and configuration ---
from app import docedit

docedit.DOCDIR = 'app/docs/'
docedit.DOCURL = '/static/docs/'
# --- / ---

TEMPLATES = os.path.join(os.path.dirname(__file__), 'templates')

# django templates setup
django.conf.settings.configure(
  TEMPLATE_DIRS=(TEMPLATES,),
  #TEMPLATE_DEBUG=True,
)


def render(tpl, values):
    return django.template.loader.render_to_string(tpl, values)

class MainPage(webapp.RequestHandler):
    def get(self):
        values = {
            'applink': '/docedit',
            'applink_text':'DocEdit Version %s' % docedit.__version__,
        }
        # [ ] link to DocEdit URL is better to be autogenerated
        #     to avoid grepping when link changes
        self.response.out.write(render('main.html', values))

class DocEdit(webapp.RequestHandler):
    def get(self):
        """
        Args:
          page: name of the page resource
        """
        # [ ] add debug messages
        pagename = self.request.get('page')
        values = dict(
            # [ ] link to action URL should be autogenerated
            actionurl = '/docedit'
        )
        if not pagename:
            # show index page
            # [ ] or choose remote one
            values.update(
                title = 'documentation sources on this server',
                pagelist = docedit.listfiles(),
            )
        elif pagename not in docedit.listfiles():
            # show error page 
            # [ ] link to the code where the error occured
            values['error'] = 'invalid page name: %s' % cgi.escape(pagename)
        else:
            # show editor page
            # [ ] add unittests
            values.update(
                title = 'a sophisticated editor for %s' % cgi.escape(pagename),
                pagename = pagename,
            )
        self.response.out.write(render('docedit.html', values))


urlmap = [
    ('/', MainPage),
    ('/docedit', DocEdit),
]


app = webapp.WSGIApplication(urlmap, debug=True)

