from flask import Blueprint, redirect, session, url_for, request, g, make_response, abort
from settings import config
from paramecio2.libraries.mtemplates import PTemplate, env_theme
from paramecio2.libraries.i18n import I18n
from paramecio2.libraries.formsutils import show_form, generate_csrf, set_extra_forms_user, pass_values_to_form
from paramecio2.libraries.db.webmodel import WebModel
from paramecio2.modules.admin.models.admin import UserAdmin
from paramecio2.libraries.keyutils import create_key_encrypt
from time import time
import os, sys
from importlib import import_module
from paramecio2.libraries.config_admin import config_admin

env=env_theme(__file__)

t=PTemplate(env)

yes_recovery_login=False
email_address='localhost'

if hasattr(config, 'yes_recovery_login'):
    yes_recovery_login=config.yes_recovery_login

if hasattr(config, 'email_address'):
    email_address=config.email_address


admin_app=Blueprint('admin_app', __name__, static_folder='static')

@admin_app.before_request
def admin_prepare():

    g.connection=WebModel.connection()
    
    if request.endpoint!='admin_app.login' and request.endpoint!='admin_app.signup':
        
        if 'login_admin' not in session:
            
            if 'remember_login_admin' in request.cookies:
                
                with g.connection.query('select count(id) as count_id from useradmin where token_login=%s', [request.cookies['remember_login_admin']]) as cursor:
                    
                    arr_count=cursor.fetchone()

                    if arr_count['count_id']==0:
                        
                        return redirect(url_for('admin_app.login'))   
                
            
            else:
            
                return redirect(url_for('admin_app.login'))   

@admin_app.after_request
def admin_finished(response):
    
    #print('pepe')
    
    g.connection.close()
    
    return response

# Load modules from admin

for app in config.apps:
    module_app=config.apps[app][0]

    module_path=os.path.dirname(sys.modules[module_app].__file__)

    if os.path.isfile(module_path+'/settings/config_admin.py'):

        config_path=module_app+'.settings.config_admin'

        a=import_module(config_path)

arr_modules_admin={}

for app_load in config_admin:
    
    #print(app)

    if len(app_load)==3:
    
        arr_modules_admin[app_load[2]+'/']=import_module(app_load[1])
        #print(app_load[1])
    elif len(app_load)==4:

        arr_modules_admin[app_load[2]+'/'+app_load[3]]=import_module(app_load[1])
        #print(app_load[1])

@admin_app.route('/admin')
@admin_app.route('/admin/<module>', methods=['GET', 'POST'])
@admin_app.route('/admin/<module>/<submodule>', methods=['GET', 'POST'])
def admin(module='', submodule=''):
    
    """
    if 'login_admin' not in session:
        return redirect(url_for('admin_app.login'))        
    """
    
    if module=='':
    
        return t.load_template('home.phtml', title=I18n.lang('admin', 'paramecio_admin', 'Paramecio admin'))
        
    else:
        
        path_module=module+'/'+submodule
        
        if path_module in arr_modules_admin:
            
            content=arr_modules_admin[path_module].admin(t=t)
            
            if type(content).__name__=='str':
            
                return t.load_template('content.phtml', title=I18n.lang('admin', 'paramecio_admin', 'Paramecio admin'), contents=content, path_module=path_module)
                
            else:
                
                return content
            
        else:
            abort(404)
        

@admin_app.route('/admin/logout')
def logout():
    
    resp=make_response(redirect(url_for('admin_app.login')))
    
    if 'login_admin' in session:
        del session['login_admin']
        
    if 'remember_login_admin' in request.cookies:
        resp.set_cookie('remember_login_admin', value='', max_age=0, expires=0, path=config.application_root)
    
    return resp

@admin_app.route('/admin/login', methods=['GET', 'POST'])
def login():
    
    #connection=WebModel.connection()
    
    user_admin=UserAdmin(g.connection)

    user_admin.yes_repeat_password=False

    user_admin.fields['password'].required=True

    user_admin.create_forms(['username', 'password'])
    
    c=user_admin.select_count()
    
    if c==0:
        return redirect(url_for('admin_app.signup'))        
    
    post={}
    
    if request.method=='POST':
        
        username=request.form['username']

        password=request.form['password']
        
        arr_user=user_admin.set_conditions('WHERE username=%s', [username]).select_a_row_where()
        
        if arr_user:
            
            if user_admin.fields['password'].verify(password, arr_user['password']):

                session['login_admin']=True
                
                resp = make_response({'error': 0})
                
                if 'remember_login' in request.form:
                    
                    remember_key=create_key_encrypt()
                    
                    user_admin.safe_query()
                    
                    user_admin.check_user=False
                    
                    user_admin.set_conditions('WHERE id=%s', [arr_user['id']]).update({'token_login': remember_key})
                    
                    timestamp=int(time())+315360000
                    
                    resp.set_cookie('remember_login_admin', value=remember_key, max_age=315360000, expires=timestamp, path=config.application_root)
                    
                return resp
            
            
            else:

                return {'error': 1, 'csrf_token': generate_csrf()}
        else:
            
            return {'error': 1, 'csrf_token': generate_csrf()}
        
        #if
    
    else:
    
        forms=show_form(post, user_admin.forms, t, yes_error=False)

        return t.load_template('login.phtml', forms=forms, yes_recovery_login=yes_recovery_login)

@admin_app.route('/admin/signup', methods=['GET', 'POST'])
def signup():

    user_admin=UserAdmin(g.connection)

    c=user_admin.select_count()
    
    if c==0:
        
        if request.method=='POST':
            
            user_admin.conditions=['WHERE privileges=%s', [2]]
             
            forms=dict(request.form)
            
            forms['privileges']=2
            
            user_admin.valid_fields=['username', 'email', 'password', 'privileges']
            
            user_admin.create_forms()
            
            if user_admin.insert(forms, False):
            
                error= {'error': 0}
                
                return error
            
            else:
                
                user_admin.check_all_fields(forms, False)
                
                pass_values_to_form(forms, user_admin.forms, yes_error=True)
                    
                session['csrf_token']=create_key_encrypt()
                
                error={'error': 1, 'csrf_token': session['csrf_token']}
                
                for field in user_admin.valid_fields:
                        
                        error[field]=user_admin.forms[field].txt_error
                
                error['repeat_password']=user_admin.forms['repeat_password'].txt_error
                
                return error
                
        else:
    
            post={}
            
            set_extra_forms_user(user_admin)
            
            forms=show_form(post, user_admin.forms, t, yes_error=False)

            return t.load_template('register.phtml', forms=forms)

    else:
        
        return redirect(url_for('.login'))

@admin_app.route('/admin/recovery_password')
def recovery_password():
    
    return ""
