# -*- mode: python -*-
# -*- coding: utf-8 -*-

"""Functions checking permissions for some common operations
"""
from flask import g, render_template
from flask_login import current_user

from app.auth.models import User
from app.models import EtudAnnotation, FormSemestre, Identite
from app.scodoc.sco_permissions import Permission
from app.scodoc import sco_exceptions


def can_suppress_annotation(annotation_id):
    """True if current user can suppress this annotation
    Seuls l'auteur de l'annotation et le chef de dept peuvent supprimer
    une annotation.
    """
    annotation = (
        EtudAnnotation.query.filter_by(id=annotation_id)
        .join(Identite)
        .filter_by(dept_id=g.scodoc_dept_id)
        .first_or_404()
    )
    if not annotation:
        raise sco_exceptions.ScoValueError("annotation inexistante !")
    return (current_user.user_name == annotation.author) or current_user.has_permission(
        Permission.EtudAddAnnotations
    )


def can_edit_suivi():
    """Vrai si l'utilisateur peut modifier les informations de suivi sur la page etud" """
    return current_user.has_permission(Permission.EtudChangeAdr)


def check_access_diretud(
    formsemestre_id, required_permission=Permission.EditFormSemestre
):
    """Check if access granted: responsable or EditFormSemestre
    Return True|False, HTML_error_page
    """
    formsemestre = FormSemestre.get_formsemestre(formsemestre_id)
    if (not current_user.has_permission(required_permission)) and (
        current_user.id not in (u.id for u in formsemestre.responsables)
    ):
        return (
            False,
            render_template(
                "sco_page.j2",
                title="Accès interdit",
                content=f"""<h2>Opération non autorisée pour {current_user}</h2>

                    <p>Responsable(s) de ce semestre : <b>{
                        ', '.join(
                        [
                            u.get_prenomnom()
                            for u in formsemestre.responsables
                        ])
                    }</b>
                    </p>
                    """,
            ),
        )
    return True, ""


def can_handle_passwd(user: User, allow_admindepts=False) -> bool:
    """True if the current user can see or change passwd info of user.
    If allow_admindepts, allow Admin from all depts (so they can view users from other depts
    and add roles to them).
    user is a User instance.
    """
    if not user:
        return False
    if current_user.is_administrator():
        return True  # super admin
    # Anyone can change his own passwd (or see his informations)
    if user.user_name == current_user.user_name:
        return True
    # If don't have permission in the current dept, abort
    if not current_user.has_permission(Permission.UsersAdmin, g.scodoc_dept):
        return False
    # Now check that current_user can manage users from this departement
    if not current_user.dept:
        return True  # if no dept, can access users from all depts !
    if (current_user.dept == user.dept) or allow_admindepts:
        return True
    return False