"""
Paramecio2fm is a series of wrappers for Flask, mako and others and construct a simple headless cms.

Copyright (C) 2023 Antonio de la Rosa Caballero

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

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
