import { Athlete, Session , Activite} from '../classes';

export interface StatsAthlete {
    nbSessions: number;
    nbSessionsPerWeek: number;
    isAlerte: boolean;
    distributions: Map<String, number>; //le nom de l'activité et son nombre
}

export function niveauAlerte(stats: StatsAthlete, seuilCritique = 0, seuilMax = 0) {
    if (stats.nbSessionsPerWeek > seuilMax) return "Alerte ! Niveau maximal atteint.";
    if (stats.nbSessionsPerWeek > seuilCritique) return "Attention! Niveau critique atteint.";
    return "Normal";
}

export function calculStatsAthlete(sessions: Session[], athlete: Athlete, debut: Date, fin: Date): StatsAthlete {
    let nb_sessions = 0;
    let nb_semaine = 1; //forcément une semaine 
    const distributions: Map<string, number> = new Map();
    const timeDiff = Math.abs(fin.getTime() - debut.getTime());
    const msPerWeek = 1000 * 3600 * 24 * 7;
    nb_semaine = Math.max(1, Math.ceil(timeDiff / msPerWeek));

    sessions.forEach(session => {
        //  verification session dans l'intervalle
        if (session.creneau < debut || session.creneau > fin) return;

        // verification athlete dans session
        if (!session.athletes.some(a => a.id === athlete.id)) return;

        //incrementation (verifie si recurent ou non)
        const increment = session.isRecurrent ? nb_semaine : 1;
        nb_sessions += increment;
        //distribution des activités
        session.activites.forEach(activite => {
            const currentCount = distributions.get(activite.nom) || 0;
            distributions.set(activite.nom, currentCount + increment);
        });

    });

    const nbSessionsPerWeek = nb_sessions / nb_semaine;
    const isAlerte = nbSessionsPerWeek > 8;

    return {
        nbSessions: nb_sessions,
        nbSessionsPerWeek: nbSessionsPerWeek,
        isAlerte: isAlerte,
        distributions: distributions
    };
}