from bottle import request, response, redirect, abort
#from settings import config
import inspect
from cuchulu.wsgiapp import app

def check_login(callback):
    def wrapper(*args, **kwargs):
        
        if 'session' in request.environ:
            
            if request.environ['session'].get('login_admin', False) and not request.environ['session'].get('verify_auth', False):
                
                #print(request.environ.get('session'))
                #print(request['bottle.route'].name)
                if request['bottle.route'].name in request.environ['session'].get('modules', []):
                    result = callback(*args, **kwargs)
                
                    return result
                else:
                    abort(403, 'You need a valid cookie for access')
            
            if request.environ['session'].get('verify_auth', False):
                redirect(app.get_url('admin_app.need_auth'))
            
        redirect(app.get_url('admin_app.login_admin'))
        
    return wrapper
"""
class CheckLoginPlugin(object):

    name = 'checklogin'
    api = 2
    
    def __init__(self, keyword='session'):
        
        self.keyword=keyword

        
    def setup(self, app):
        ''' Make sure that other installed plugins don't affect the same keyword argument.'''
        for other in app.plugins:
            if not isinstance(other, SessionPlugin): continue
            if other.keyword == self.keyword:
                raise PluginError("Found another login plugin with "\
                "conflicting settings (non-unique keyword).")

    def apply(self, callback, context):

        # Test if the original callback accepts a 'session' keyword.
        # Ignore it if it does not need a login handle.
        
        conf = context.config.get('checklogin') or {}
        
        keyword = conf.get('keyword', self.keyword)
        
        args = inspect.getfullargspec(context.callback)[0]
    
        if keyword not in args:
            return callback
        
        def wrapper(*args, **kwargs):
            
            if 'session' in request.environ:
                
                if request.environ['session'].get('login_admin', 1):
                
                    rv=callback(*args, **kwargs)
                
                    return rv   
            
            redirect(app.get_url('admin_app.home_admin'))

        return wrapper
"""
