from settings import config
from cuchulu.modules.admin.models.admin import UserAdmin
from cuchulu.libraries.generate_admin_class import GenerateAdminClass
from cuchulu.libraries.i18n import I18n, PGetText
from cuchulu.libraries.db.coreforms import SelectForm
from cuchulu.libraries.db.coreforms import HiddenForm
import copy
from cuchulu.modules.admin import admin_app, t as admin_t
from cuchulu.libraries.urls import url_for
from cuchulu.libraries.sessionplugin import get_session

pgettext=PGetText(__file__+'/../')

_=pgettext.gettext

t=copy.copy(admin_t)

@admin_app.get('/admin/ausers', name='admin_app.ausers')
@admin_app.post('/admin/ausers', name='admin_app.ausers')
def ausers(db=True):
    
    connection=db
    
    user_admin=UserAdmin(connection)
    
    user_admin.fields['privileges'].name_form=SelectForm
    
    user_admin.fields['disabled'].name_form=SelectForm
    
    user_admin.fields['double_auth'].name_form=SelectForm
    
    user_admin.fields['last_login'].name_form=HiddenForm
    
    user_admin.fields['dark_theme'].name_form=SelectForm
    
    user_admin.create_forms(['username', 'password', 'email', 'privileges', 'lang', 'dark_theme', 'disabled', 'double_auth', 'last_login', 'privileges'])
    
    user_admin.forms['privileges'].arr_select={0: _('Without privileges'), 1: _('Selected privileges'), 2: _('Administrator')}
    
    user_admin.forms['disabled'].arr_select={0: _('User enabled'), 1: _('User disabled')}
    
    user_admin.forms['double_auth'].arr_select={0: _('No'), 1: _('Yes')}
    
    user_admin.fields['password'].protected=False
    
    user_admin.forms['dark_theme'].arr_select={0: _('Light theme'), 1: _('Dark theme')}
    
    user_admin.check_user=False
    user_admin.check_email=False
    
    url=url_for('admin_app.ausers')
    
    admin=GenerateAdminClass(user_admin, url, t)
    
    admin.list.fields_showed=['username']
    
    admin.list.search_fields=['username']
    
    admin.arr_fields_edit=['username', 'password', 'repeat_password', 'email', 'lang', 'dark_theme', 'double_auth', 'disabled', 'last_login', 'privileges']
    
    admin.post_update=update_lang
    
    form_admin=admin.show()
    
    if type(form_admin).__name__=='str':
        
        return t.load_template('content.phtml', title=_('Users edit'), contents=form_admin, path_module='admin_app.ausers')    
    else:
        
        return form_admin    


def update_lang(admin, item_id):
    
    arr_row=admin.model.select_a_row(item_id)
    
    session=get_session()
    
    session['lang']=arr_row.get('lang', I18n.get_default_lang())
    
    return True
