import os

import wtforms as wtf
from flask import url_for, request
from flask_admin import Admin, AdminIndexView, expose
from flask_admin.contrib import sqla
from flask_admin.contrib import fileadmin
from flask_admin.menu import MenuLink
from flask_security import current_user
from werkzeug.exceptions import abort
from werkzeug.utils import redirect

from PDMI.models import db, Users, Modules, ModuleVersions, Roles


# from server.main import security
# Pour les fichiers
# def _imagename_uuid1_gen(obj, file_data):
#    _, ext = os.path.splitext(file_data.filename)
#    uid = uuid.uuid1()
#    return secure_filename('{}{}'.format(uid, ext))


class BooleanField(wtf.BooleanField):
    """Boolean field without form-control class"""

    def __call__(self, *args, **kwargs):
        # Adding `readonly` property to `input` field
        kwargs.update({'class': kwargs.get('class', '').replace("form-control", "")})
        return super(BooleanField, self).__call__(*args, **kwargs)


class ConfigurableView(sqla.ModelView):
    roles = []
    details_modal = True
    edit_modal = True
    create_modal = True

    def is_accessible(self):
        if not current_user.is_active or not current_user.is_authenticated:
            return False
        if current_user.has_role("superadmin"):
            return True
        for role in self.roles:
            if current_user.has_role(role):
                return True
        return False

    def _handle_view(self, name, **kwargs):
        """
        Override builtin _handle_view in order to redirect users when a view is not accessible.
        """
        if not self.is_accessible():
            if current_user.is_authenticated:
                # permission denied
                abort(403)
            else:
                # login
                return redirect(url_for('security.login', next=request.url))


class SuperUserView(ConfigurableView):
    roles = []
    # Affichage de la table
    column_editable_list = ['active', 'username', 'email', ]
    column_searchable_list = ['active', 'username', 'email', ]
    column_filters = ['active', 'username', 'email', 'roles', ]
    column_exclude_list = ['password', ]
    # Formulaire
    form_excluded_columns = ['password', ]
    form_columns = ['username', 'email', 'roles', 'active', ]
    form_overrides = {
        "active": BooleanField,
    }
    # Details
    column_details_exclude_list = ['password', ]

class RolesView(ConfigurableView):
    roles = []



class ModuleView(ConfigurableView):
    inline_models = (
        (
            ModuleVersions,
            {
                'form_label': "Versions",
                'form_columns': ('id', 'version',)
            }
        ),
    )


# Index view
class IndexView(AdminIndexView):
    @expose('/')
    def index(self):
        return self.render('admin/index.html')


admin = Admin(  # server,
    index_view=IndexView(menu_icon_type='fa',
                         menu_icon_value='fa-home', ),
    name='PDMI',
    template_mode='bootstrap3',
    category_icon_classes={
        'Administration': 'fa fa-cogs',
    },
    endpoint='administration',
    disconnect_route="security.logout",
    connect_route="security.login",
    favicon="favicon.ico"
)

admin.add_view(SuperUserView(
    Users,
    db.session,
    menu_icon_type='fa',
    menu_icon_value='fa-users',
    name="Administrateurs",
    category="Administration",
    endpoint="admin.users"
))

admin.add_view(RolesView(
    Roles,
    db.session,
    menu_icon_type='fa',
    menu_icon_value='fa-users',
    name="Roles",
    category="Administration",
    endpoint="admin.roles"
))

admin.add_view(ModuleView(
    Modules,
    db.session,
    menu_icon_type="fa",
    menu_icon_value="fa-gears",
    name="Modules",
    category="Modules",
    endpoint="admin.modules"
))

admin.add_view(fileadmin.FileAdmin('modules', 
'/files/', name='Module Files'))
