import os

from rlextra.preppy import preppy
from rlextra.ers.webapp import WebApp
from rlextra.forms.question import Questionnaire, QSection

class PersonalDetailsSection(QSection):

    def fixup(self):
        if self.skipLegalRequirements.value:
            self.getParent().legalRequirements.hidden = 1

class QDFExampleQuestionnaire(Questionnaire):

    sectionNameClassMap = Questionnaire.sectionNameClassMap.copy()
    sectionNameClassMap.update({
        'personalDetails': PersonalDetailsSection,
        })


class QDFExampleApp(WebApp):

    def __init__(self, **kw):

        #define qdfDtdDir - apps may add tags so need to override this.
        import rlextra.forms        
        self.qdfDtdDir = os.path.dirname(rlextra.forms.__file__)

        #define a qdfSearchPath attribute.  Put current
        #directory and any subdir called 'forms' on it
        #as a sensible default.  The cgi or config file
        #can override this.
        self.qdfSearchPath = [os.getcwd()]
        if os.path.isdir('forms'):
            self.qdfSearchPath.append('forms')
        #add my own test folder
        self.qdfSearchPath.append(os.path.dirname(rlextra.forms.__file__) + os.sep + 'test')

        WebApp.__init__(self, questionnaireClass=QDFExampleQuestionnaire, **kw)

    def action_start(self, request, response):
        qdf = 'example_hello'
        response.write('<html><head><title>ReportLab Forms Test Harness</title></head><body>'
                       '<p>Click here to test a form:</p>'
                       '<a href="%s?action=showQuestionnaire&qdf=%s">%s</a>'
                       '</body></html>' % (request.getScriptURL(), qdf, qdf))

    def loadQuestionnaire(self, name):
        """Find a form on the path and load it.

        Return a questionnaire object, or raise an error if
        not found"""

        qdfFileName = name + '.qdf'
        fullFileName = None
        for searchDir in self.qdfSearchPath:
            if os.path.isfile(searchDir + os.sep + qdfFileName):
                fullFileName = searchDir + os.sep + qdfFileName
                continue

        if not fullFileName:
            raise Exception('Questionnaire file %s not found!' % qdfFileName)

        #now we can instantiate it
        obj = self.questionnaireClass(fullFileName)
        return obj

    def action_showQuestionnaire(self, request, response):

        """Displays a questionnaire in stages.

        The following parameters and modes are supported.

        qdf (required) - name of qdf file, without the extension.
            This app searches the rlextra\forms\test directory
            and the .\forms directory for files.

        submittedSection - name of section being submitted.  If not
            provided, the first display sections is shown.

        section - request a specified section, rather than letting
            the Questionnaire and WebApp determine the next section
            from the submitted section.  Takes precedence over
            submittedSection.

        allSections - display all sections at once.  Takes precedence
            over submittedSection and section.

        # XXX rename
        submitting - performing final submission.  In this case, we
            perform the finalAction after executing any standard
            Questionnaire hook methods.

        finalAction - the final action when the last section is
            submitted.

        sample - if present, canned sample values appear in the form.

        """
        params = request.params
        qdf = params.get('qdf', 'example_hello')
        submittedSection = params.get('submittedSection', None)
        section = params.get('section', None)
        allSections = params.get('allSections', 0)
        finalAction = params.get('finalAction', 'echo')
        submitting = params.get('submitting', 0)

        questionnaire = self.loadQuestionnaire(qdf)
        if params.has_key('sample'):
            questionnaire.makeSample()
        else:
            questionnaire.setTextDictionary(params)

        if submitting:
            request.params['action'] = finalAction
            self._handleRequest(request, response)
        else:
            if allSections:
                section = Questionnaire.AllSections
            try:
                section, form = questionnaire.makeNextHtmlForm(
                    request.getScriptURL(), finalAction, qdf,
                    submittedSection, section)
            except Questionnaire.SectionNotFoundError, e:
                response.write(str(e))
                return
                #raise

            params = {
                'JSV': questionnaire.JSV,
                'form': form,
                }
            m = preppy.getModule('template', directory="views")
            response.write(m.getOutput(params))
