import flask_login
from flask import flash, redirect, request, url_for
from flask_admin.contrib.sqla import ModelView
from markupsafe import Markup


# Create customized model view class
class ResultsView(ModelView):
    can_edit = False
    can_delete = False
    can_create = False
    column_default_sort = ("result.created_at", True)

    def is_accessible(self):
        """Check if current user can access admin interface"""
        return flask_login.current_user.is_authenticated

    def inaccessible_callback(self, name, **kwargs):
        """Redirect to login if not accessible"""
        flash("Please login to access this page.", "danger")
        return redirect(url_for("admin.login_view", next=request.url))

    @staticmethod
    def _list_thumbnail(view, _context, model, _name):
        data = ""
        data += f'<img src="/attachments{model.result.attachment.path}.original.jpg" width="100" />'

        return Markup(data)

    column_formatters = {
        "path": _list_thumbnail,
    }

    column_list = ["result", "path", "beerd", "probability"]
