from paramecio.modules.admin.models.admin import UserAdmin
from bottle import request
from paramecio.citoplasma.sessions import get_session
from paramecio.citoplasma.urls import redirect, make_url
from paramecio.cromosoma.webmodel import WebModel
import inspect

class LoginPlugin(object):

    name = 'login'
    api = 2
    
    def __init__(self, keyword='login'):
        
        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, LoginPlugin): 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 'db' keyword.
        # Ignore it if it does not need a login handle.
        
        conf = context.config.get('login') or {}
        
        keyword = conf.get('keyword', self.keyword)
        
        args = inspect.getfullargspec(context.callback)[0]
        
        if keyword not in args:
            return callback
        
        def wrapper(*args, **kwargs):
            
            s=get_session()
            
            if 'login' in s:

                rv = callback(*args, **kwargs)
                
                return rv
            
            else:
                #Check if remember_login cookie
                #, secret=config.key_encrypt

                redirect(make_url('login'))
            
        # Replace the route callback with the wrapped one.
        return wrapper
        
        
class DbPlugin(object):

    name = 'db'
    api = 2
    
    def __init__(self, keyword='db'):
        
        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, DbPlugin): 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 'db' keyword.
        # Ignore it if it does not need a login handle.
        
        conf = context.config.get('db') or {}
        
        keyword = conf.get('keyword', self.keyword)
        
        args = inspect.getfullargspec(context.callback)[0]
    
        if keyword not in args:
            return callback
        
        def wrapper(*args, **kwargs):
        
            kwargs['db']=WebModel.connection()

            rv = callback(*args, **kwargs)
            
            kwargs['db'].close()
                
            return rv

        return wrapper
            
                    
        



