from cuchulu.libraries.db.webmodel import WebModel
from settings import config
from cuchulu.libraries.db.extrafields.passwordfield import PasswordField
from cuchulu.libraries.i18n import I18n, PGetText
from bottle import request, redirect
from cuchulu.wsgiapp import app
from bottle import abort
from cuchulu.libraries.sessionplugin import get_session
from cuchulu.libraries.urls import url_for

try:
    import ujson as json
except:
    import json

modules_access=[]

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'))
        """
        
        db=kwargs.get('db', WebModel.connection())
        
        session=get_session()
        
        if 'login_admin' not in session:
            
            # Disabled remember login
            
            """
            if 'remember_login_admin' in request.cookies:
                
                try:
                
                    arr_cookie=json.loads(request.cookies['remember_login_admin'])
                    
                except:
                    
                    arr_cookie=(0, '')
                    
                #print(arr_cookie)
                #with g.connection.query('select count(id) as count_id from useradmin where token_login=%s', [request.cookies['remember_login_admin']]) as cursor:
                with db.query('select id, token_login, dark_theme from useradmin where id=%s', [arr_cookie[0]]) as cursor:
                    
                    arr_user=cursor.fetchone()
                    
                    if arr_user:
                    
                        passfield=PasswordField('token_login')
                        
                        if passfield.verify(arr_cookie[1], arr_user['token_login']):
                            
                            session['login_admin']=True
                            session['user_id']=arr_user['id']
                            
                            if arr_user['dark_theme']:
                                session['theme']='1'
                            else:
                                session['theme']='0'
                            
                            session['lang']=arr_user.get('lang', I18n.default_lang)
                            
                        else:
                            
                            session.clear()
                            
                            session.save()

                            url_redirect=url_for('admin_app.login', _external=False)
                            
                            return redirect(url_redirect)   
                    else:
                        
                        session.clear()
                        
                        session.save()
                        
                        url_redirect=url_for('admin_app.login', _external=False)
                            
                        return redirect(url_redirect)   
                        
            else:
                
            """
            
            url_redirect=url_for('admin_app.login')
                
            return redirect(url_redirect)   
            
            pass
        else:
            
            if not session.get('verify_auth', True):
                    
                url_redirect=url_for('admin_app.need_auth')
                    
                return redirect(url_redirect)   
            
            result = callback(*args, **kwargs)
                
            return result
    
    return wrapper

"""
def admin_prepare():

    conn=WebModel.connection()
    
    if request.endpoint!='admin_app.login' and request.endpoint!='admin_app.signup' and request.endpoint!='admin_app.need_auth' and request.endpoint!='admin_app.auth_check':
        
        if 'login_admin' not in session:
            
            if 'remember_login_admin' in request.cookies:
                
                try:
                
                    arr_cookie=json.loads(request.cookies['remember_login_admin'])
                    
                except:
                    
                    arr_cookie=(0, '')
                    
                #print(arr_cookie)
                #with g.connection.query('select count(id) as count_id from useradmin where token_login=%s', [request.cookies['remember_login_admin']]) as cursor:
                with g.connection.query('select id, token_login, dark_theme from useradmin where id=%s', [arr_cookie[0]]) as cursor:
                    
                    arr_user=cursor.fetchone()
                    
                    if arr_user:
                    
                        passfield=PasswordField('token_login')
                        
                        if passfield.verify(arr_cookie[1], arr_user['token_login']):
                            
                            session['login_admin']=True
                            session['user_id']=arr_user['id']
                            
                            if arr_user['dark_theme']:
                                session['theme']='1'
                            else:
                                session['theme']='0'
                            
                            session['lang']=arr_user.get('lang', I18n.default_lang)
                            
                        else:
                            
                            session.clear()

                            url_redirect=config.domain_url+url_for('admin_app.login', _external=False)
                            
                            return redirect(url_redirect)   
                    else:
                        
                        session.clear()
                        
                        url_redirect=config.domain_url+url_for('admin_app.login', _external=False)
                            
                        return redirect(url_redirect)   
                        
            else:
                
                url_redirect=config.domain_url+url_for('admin_app.login', _external=False)
                
                return redirect(url_redirect)   
        else:
            
            
            if request.endpoint!='admin_app.logout':
            
                if not session.get('verify_auth', True):
                    
                    url_redirect=config.domain_url+url_for('admin_app.need_auth', _external=False)
                    
                    return redirect(url_redirect)   

def admin_finished(response):
    
    g.connection.close()
    
    return response
"""
