# -*- coding: UTF-8 -*-
###########################################################################
# Eole - 2013
# Copyright Pole de Competence Eole  (Ministere Education - Academie Dijon)
# Licence CeCill  cf /root/LicenceEole.txt
# eole@ac-dijon.fr
#
# genconfig.py
#
# Fichier d'initialisation d'un ressource WSGI pour servir eolegenconfig
# dans le serveur web de Zéphir
#
###########################################################################
import base64, os
from twisted.web.wsgi import WSGIResource
from twisted.web import static
from twisted.internet import reactor
from twisted.python import log
from flask import Flask

from zephir.web.template.page import PageEole, FileEole, IPreferences, check_auth, require_auth #, EoleProxy
from zephir.web.template.design import proxy, get_user, get_password
from zephir.web.html.erreur import backend
from zephir.web import config

from zephir.web.zephirgenconfig import app


class GenConfig(PageEole):

    def __init__(self):
        self.app = app
        # permet ou non l'affichage des logs de l'application dans les logs zephir_web
        self.app.debug = False
        # configuration du répertoire des templates hors eoleflask
        self.app.template_folder = '/usr/share/eole/flask/genconfig/templates'
        self.app.zephir_proxy = None
        self.wsgi = WSGIResource(reactor, reactor.getThreadPool(), self.app)
        PageEole.__init__(self)

    def getChild(self, path, request):
        if path == b"static":
            return FileEole(os.path.join(config.FLASKDIR, 'genconfig', 'static'))
        request.prepath.pop()
        if path != b'genconfig':
            request.postpath.insert(0, path)
        if not check_auth(request):
            return require_auth(request)
        # on force le header 'Authorization' pour le retrouver dans Flask
        auth_value = 'Basic ' + base64.encodebytes(get_user(request).encode() + b':' + get_password(request).encode()).decode()
        request.requestHeaders.setRawHeaders('Authorization', [auth_value])
        return self.wsgi

    def render(self, request):
        # on force le header 'Authorization' pour le retrouver dans Flask
        auth_value = 'Basic ' + base64.encodebytes('{0}:{1}'.format(get_user(request), get_password(request)))
        request.requestHeaders.setRawHeaders('Authorization', [auth_value])
        return self.wsgi.render(request)
