#!/usr/bin/env python

import falcon
from controllers import util
from models import main
from settings import MV


def handle_404(req, resp):
    id_session = req.cookies.get('beaker.session.id', '')
    if id_session:
        raise falcon.HTTPTemporaryRedirect('/main')
    raise falcon.HTTPTemporaryRedirect('/')


def get_template(req, resp, resource):
    session = req.env['beaker.session']
    resp.content_type = 'text/html'
    data = {'username': session.get('user', '')}
    resp.body = util.get_template(resource.template, data)


# ~ def static(req, res):
    # ~ path = PATH_STATIC + req.path
    # ~ if util.is_file(path):
        # ~ res.content_type = util.get_mimetype(path)
        # ~ res.stream, res.stream_len = util.get_stream(path)
        # ~ res.status = falcon.HTTP_200
    # ~ else:
        # ~ res.status = falcon.HTTP_404


class AuthMiddleware(object):

    def process_response(self, req, resp, resource):
        pass

    def process_resource(self, req, resp, resource, params):
        session = req.env['beaker.session']
        user = session.get('userobj', None)
        id_session = req.cookies.get('beaker.session.id', '')

        if req.path == '/values/titlelogin':
            pass
        elif req.path == '/empresas' or req.path == '/values/empresas':
            if MV:
                pass
            else:
                raise falcon.HTTPTemporaryRedirect('/')
        elif id_session and req.path == '/admin':
            if user is None:
                raise falcon.HTTPTemporaryRedirect('/')
            elif not user.es_admin and not user.es_superusuario:
                raise falcon.HTTPTemporaryRedirect('/main')
        elif not id_session and req.path != '/':
            raise falcon.HTTPTemporaryRedirect('/')
        elif id_session and user is None:
            session.delete()
            if req.path == '/main':
                raise falcon.HTTPTemporaryRedirect('/')


class JSONTranslator(object):

    #~ def process_request(self, req, resp):
        #~ pass

    def process_response(self, req, resp, resource):
        if 'result' not in req.context:
            return

        if '/doc/' in req.path:
            resp.body = req.context['result']
            return

        if 'blob' in req.context:
            resp.body = req.context['blob']
            return

        resp.body = util.dumps(req.context['result'])


class ConnectionMiddleware(object):

    #~ def process_request(self, req, resp):
    def process_resource(self, req, resp, resource, params):
        id_session = req.cookies.get('beaker.session.id', '')
        session = req.env['beaker.session']
        rfc = session.get('rfc', '')
        if id_session and rfc:
            opt = util.get_con(rfc)
            if opt:
                main.conectar(opt)
            else:
                raise falcon.HTTPTemporaryRedirect('/')

    def process_response(self, req, resp, resource):
        main.desconectar()

