from flask_admin import Admin, helpers as admin_helpers
from flask_admin.contrib.sqla import ModelView
from flask_security import current_user, utils
from wtforms.fields import PasswordField

from libertywiki.db import session
from libertywiki.models import User, Role


class UserAdmin(ModelView):
    """A custom view for user administration"""
    column_exclude_list = ('password',)
    form_excluded_columns = ('password',)
    column_auto_select_related = True

    def is_accessible(self):
        """Prevent administration of users from users without the "admin" role"""
        return current_user.has_role('admin')

    def scaffold_form(self):
        """Remove the password field so that we can bypass it and set the password manually"""
        form_class = super().scaffold_form()
        form_class.password2 = PasswordField('New Password')
        return form_class

    def on_model_change(self, form, model, is_created):
        """Update the password when the user is saved"""
        if len(model.password2):
            model.password = utils.encrypt_password(model.password2)


class RoleAdmin(ModelView):
    """A custom view for role administration"""

    def is_accessible(self):
        """Prevent administration of roles from users without the "admin" role"""
        return current_user.has_role('admin')


def setup_admin(app):
    """Set up the admin interface"""
    admin = Admin(app, 'LibertyWiki Admin', base_template='admin/my_master.html', template_mode='bootstrap4')
    admin.add_view(UserAdmin(User, session))
    admin.add_view(RoleAdmin(Role, session))
    return admin, admin_helpers
