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

##############################################################################
#
# Gestion scolarite IUT
#
# Copyright (c) 1999 - 2022 Emmanuel Viennet.  All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   Emmanuel Viennet      emmanuel.viennet@viennet.net
#
##############################################################################

"""Fonctions de calcul des moyennes de semestre (indicatives dans le BUT)
"""
import numpy as np
import pandas as pd


def compute_sem_moys(etud_moy_ue_df, modimpl_coefs_df):
    """Calcule la moyenne générale indicative
    = moyenne des moyennes d'UE, pondérée par la somme de leurs coefs

    etud_moy_ue_df: DataFrame, colonnes ue_id, lignes etudid
    modimpl_coefs_df: DataFrame, colonnes moduleimpl_id, lignes UE

    Result: panda Series, index etudid, valeur float (moyenne générale)
    """
    moy_gen = (etud_moy_ue_df * modimpl_coefs_df.values.sum(axis=1)).sum(
        axis=1
    ) / modimpl_coefs_df.values.sum()
    return moy_gen


def comp_ranks_series(notes: pd.Series):
    """Calcul rangs à partir d'une séries ("vecteur") de notes (index etudid, valeur numérique)
    en tenant compte des ex-aequos
    Le resultat est: { etudid : rang } où rang est une chaine decrivant le rang
    """
    notes = notes.sort_values(ascending=False)  # Serie, tri par ordre décroissant
    rangs = pd.Series(index=notes.index, dtype=str)  # le rang est une chaîne
    N = len(notes)
    nb_ex = 0  # nb d'ex-aequo consécutifs en cours
    notes_i = notes.iat
    for i, etudid in enumerate(notes.index):
        # test ex-aequo
        if i < (N - 1):
            next = notes_i[i + 1]
        else:
            next = None
        val = notes_i[i]
        if nb_ex:
            srang = "%d ex" % (i + 1 - nb_ex)
            if val == next:
                nb_ex += 1
            else:
                nb_ex = 0
        else:
            if val == next:
                srang = "%d ex" % (i + 1 - nb_ex)
                nb_ex = 1
            else:
                srang = "%d" % (i + 1)
        rangs[etudid] = srang
    return rangs
