from cuchulu.modules.admin2.models.admin import UserAdmin2
from cuchulu.modules.admin2.app import admin_app
from cuchulu.modules.admin2.libraries.config import modules_admin, modules_admin_icons
from cuchulu.libraries.mtemplates import PTemplate, env_theme
from cuchulu.libraries.i18n import I18n, PGetText
import cuchulu.modules.admin2.libraries.i18n as i18n_lang
import os
#from cuchulu.libraries.lists import SimpleList
from cuchulu.libraries.generate_admin_class import GenerateAdminClass
from cuchulu.libraries.db.formsutils import show_form
from cuchulu.libraries.db.coreforms import SelectForm
from cuchulu.libraries.db.coreforms import PasswordForm
from cuchulu.libraries.db.coreforms import HiddenForm
from cuchulu.wsgiapp import app
from cuchulu.libraries.db.webmodel import WebModel
from cuchulu.modules.admin2.models.admin import UserAdmin2, PrivilegesModule2
from cuchulu.libraries.urls import add_get_parameters
from cuchulu.modules.admin2.libraries.config import modules_admin

env=env_theme(__file__)

t=PTemplate(env)

gtext=PGetText(__file__)

_=gtext.gettext


#t.env.directories=admin_t.env.directories
"""
tpl_path=os.path.dirname(__file__).replace('/admin', '')+'/templates/admin'

if t.env.directories[1]!=tpl_path:
    t.env.directories.insert(1, tpl_path)
"""
#modules_admin.append(['menu_users', 'people-circle', True])

def admin_users():
    
    return _('Admin users')
    
def edit_admin_users():
    
    return _('Edit Admin users')

modules_admin['admin_app.admin_users']=[[admin_users, 'people-circle', ''], [edit_admin_users, 'people-circle', ['admin_app.admin_permissions']]]

modules_admin_icons['admin_app.admin_users']='<symbol id="people-circle" viewBox="0 0 16 16"><path d="M11 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0z"/><path fill-rule="evenodd" d="M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8zm8-7a7 7 0 0 0-5.468 11.37C3.242 11.226 4.805 10 8 10s4.757 1.225 5.468 2.37A7 7 0 0 0 8 1z"/></symbol>'

@admin_app.get('/ausers', name="admin_app.admin_users")
@admin_app.post('/ausers', name="admin_app.admin_users")
def admin_users(session={}):
    
    #i18n=I18n('admin2')
    
    db=WebModel.connection()
    
    user_admin=UserAdmin2(db)
    
    user_admin.fields['privileges'].name_form=SelectForm
    
    user_admin.fields['dark_theme'].name_form=SelectForm
    
    user_admin.fields['double_auth'].name_form=SelectForm
    
    user_admin.create_forms(['username', 'password', 'email', 'privileges', 'lang', 'dark_theme', 'double_auth'])
    
    user_admin.forms['privileges'].arr_select={0: _('Without privileges'), 1: _('Selected privileges'), 2: _('Administrator')}
    
    user_admin.forms['dark_theme'].arr_select={0: _('Light theme'), 1: _('Dark theme')}
    
    user_admin.forms['double_auth'].arr_select={0: _('No'), 1: _('Yes')}
    
    user_admin.fields['password'].protected=False
    
    url=app.get_url('admin_app.admin_users')
    
    admin=GenerateAdminClass(user_admin, url, t)
    
    admin.list.fields_showed=['username', 'email', 'double_auth', 'privileges', 'last_login']
    
    admin.list.search_fields=['username']
    
    admin.arr_fields_edit=['username', 'password', 'repeat_password', 'email', 'privileges', 'lang', 'dark_theme', 'double_auth']

    admin.list.arr_extra_options=[user_options]
    
    slist=admin.show()
    
    db.close()

    return t.load_template('users.phtml', title=_('Admin users'), tlang=_, module_selected='admin_app.admin_users', slist=slist, session=session)

@admin_app.get('/ausers/permissions/<user_id:int>', name="admin_app.admin_permissions")
@admin_app.post('/ausers/permissions/<user_id:int>', name="admin_app.admin_permissions")
def admin_permissions(user_id, session={}):
    
    db=WebModel.connection()
    
    user_admin=UserAdmin2(db)
    
    arr_user=user_admin.select_a_row(user_id, ['username'])
    
    if arr_user:
    
        priv=PrivilegesModule2(db)
        
        url=app.get_url('admin_app.admin_permissions', user_id=user_id)
        
        admin=GenerateAdminClass(priv, url, t)
        
        admin.list.fields_showed=['module']
        
        admin.list.search_fields=['module']
        
        priv.fields['module'].name_form=SelectForm
        
        #arr_modules={k:v[0] for k, v in modules_admin.items()}
        arr_modules={}
        
        for k, v in modules_admin.items():
            if type(v[0]).__name__=='function':
                arr_modules[k]=v[0]()
            else:
                arr_modules[k]=v[0]
        
        priv.fields['user_id'].name_form=HiddenForm
        
        priv.fields['user_id'].extra_parameters=[]
        
        priv.fields['user_id'].default_value=user_id

        priv.create_forms()
        
        priv.set_conditions('WHERE user_id=%s', [user_id])
        
        priv.forms['module'].arr_select=arr_modules
        
        #print(user_id)
        #with db.query('select *')
        
        privileges_admin=admin.show()
    
    else:
        arr_user={'username': _('User not found')}
        privileges_admin=''
    
    db.close()
    
    return t.load_template('access.phtml', title=_('Users permissions'), privileges_admin=privileges_admin, user=arr_user, module_selected='admin_app.admin_users')

def user_options(url, id, arr_row):
    
    options=[]
    options.append('<a href="'+add_get_parameters(url, op_admin=1, id=id)+'">'+_('Edit')+'</a>')
    if arr_row['privileges']==1:
        options.append('<a href="'+app.get_url('admin_app.admin_permissions', user_id=id)+'">'+_('User access')+'</a>')
    options.append('<a href="'+add_get_parameters(url, op_admin=3, id=id)+'">'+_('Delete')+'</a>')
    return options
