from flask import g, session, redirect, url_for
from functools import wraps
from paramecio2.libraries.db.webmodel import WebModel

login_name='login'
login_url='.login'

def db(f):
    
    @wraps(f)
    
    def wrapper(*args, **kwds):
        
        """Wrapper function for add db connection to your flask function
    
        Wrapper function for add db connection to your flask function. Also close the connection if error or function exection is finished.
        
        Args:
            *args (mixed): The args of function
            **kwds (mixed): Standard python extra arguments of function
            
        Returns:
            wrapper (function): Return the wrapper.
        """
        
        g.connection=WebModel.connection()
        
        try:
        
            code=f(*args, **kwds)
        
            g.connection.close()
            
        except:
            
            g.connection.close()
            
            raise
        
        return code
        
    return wrapper

def login_site(f):
    
    @wraps(f)
    
    def wrapper(*args, **kwds):
        
        """Wrapper function for check login in your flask function
    
        Wrapper function for check a login session in your flask function. If 
        
        Args:
            *args : The args of function
            **kwds : Standard python extra arguments of function
        
        Returns:
            wrapper (function): Return the wrapper.
        """
        
        
        if not login_name in session:
            
            return redirect(url_for(login_url))
            
        else:
            
            return f(*args, **kwds)
   
    return wrapper
