import api, { activiteService, athleteService, coachService, sessionService } from "./api";
import { Activite, Admin, Athlete, Coach, Session, User } from "./classes";
import Keycloak from 'keycloak-js'
import { AdminDTO, AthleteDTO, CoachDTO } from "./classesDTO";

//debug:
export function delay(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

//UPDATE /////////////////////////////////////////////////////////

//COACH / ATHLETE

/*
retourne l'utilisateur lié à l'identifiant keyloack
*/
export async function getUser(keycloak:Keycloak): Promise<User|null>{
    try {
        const roles = keycloak.tokenParsed?.realm_access?.roles
        if(roles!=null){
            if(roles.includes("admin")){
                const response = await athleteService.create(keycloak.tokenParsed);
                const admin = new Admin(response.data);
                return admin;
            }
            else if(roles.includes("coach")){
                const response = await coachService.create(keycloak.tokenParsed);
                const coach = new Coach(response.data);
                return coach;
            }
            else if(roles.includes("athletes")){
                const response = await athleteService.create(keycloak.tokenParsed);
                const athlete = new Athlete(response.data);
                return athlete;
            }
            console.error("Error roles inconnu");
        }

        return null;
    }
    catch (error) {
        console.error("Error fetching user:", error);
        return null;
    }   
}

/*
retourne toutes les Session dont l'user est inscrit
*/
export async function updateSessionsOfUserAPI(user:Coach|Athlete, min: Date|null, max: Date|null){
    try {
        const response = await api.get<Session[]>(`/users/${user.id}/sessions`, {
            params: {
                minDate: min ? min.toISOString() : undefined,
                maxDate: max ? max.toISOString() : undefined
            }
        });
        return response.data;
    } catch (error) {
        console.error("Error fetching sessions for user:", error);
        return [];
    }
}

export async function updateActivitiesOfSessionAPI(session:Session){
    try {
        const response = await api.get<Activite[]>(`/sessions/${session.id}/activities`);
        session.activites = response.data;
    } catch (error) {
        console.error("Error fetching activities for session:", error);
    }
    
}

export async function subscribeSessionAPI(user:User, session:Session):Promise<boolean>{
    try {
        await api.post(`/sessions/${session.id}/subscribe`);
        return true;
    } catch (error) {
        console.error("Error subscribing to session:", error);
        return false;
    }
}

export async function unsubscribeSessionAPI(user:User, session:Session):Promise<boolean>{
    try {
        await api.post(`/session/${session.id}/unsubscribe`);
        return true;
    } catch (error) {
        console.error("Error unsubscribing from session:", error);
        return false;
    }
}

// ADMIN :

export async function updateAllSessionAPI(min: Date, max: Date){
    //TODO
}

export async function updateAllUserAPI(){

}

// POST /////////////////////////////////////////////////////////

// COACH ADMIN 
export async function createSessionAPI(sessionDTO: any): Promise<Session> {
    try {
        const response = await api.post<Session>("/session/create", sessionDTO);
        return response.data;
    } catch (error) {
        console.error("Error creating session:", error);
        throw error;
    }
}

export async function postActivityAPI(session: Session, activity: Activite){
    try {
        const response = await api.post<Activite>(`/session/${session.id}/activities`, activity);
        return response.data;
    } catch (error) {
        console.error("Error creating activity:", error);
        throw error;
    }
}

export async function postAthlete(athlete: Athlete):Promise<Athlete>{
   try {
        //const response = await api.post<Athlete>("/athlete/create/",athlete.toDTO);
        const response = await athleteService.create(athlete.toDTO());
        console.log(response);
        return new Athlete(response.data);
    } catch (error) {
        console.error("Error fetching coachs:", error);
        throw error;
    }
}

export async function postSession(session: Session){
    try {
        const data = {
                name: session.name,
                creneau: session.creneau, // string ISO OK
                duree: session.duree,
                isRecurrent: session.isRecurrent,

                coachId: session.coach?.id,
                groupe: session.groupe ? session.groupe  : undefined,
        }

        const response = await sessionService.create(data);
        session.id = response.data.id; //TODO ?

        session.activites.forEach(activite => {
            const data2 = {
                name: activite.nom,
                duree: activite.duree,
                date: activite.data,
                theme: activite.theme,
                sessionId: session.id, //TODO
            }
            activiteService.create(data2);
            //     console.log("Session créée");
        });
    } catch (error) {
        console.error("Error post Session:", error);
        throw error;
    }
}

export async function postAdmin(athlete: Admin):Promise<Admin>{
   try {
        const response = await api.post<Admin>("/admin/create/",athlete);
        console.log(response);
        return response.data;
    } catch (error) {
        console.error("Error fetching coachs:", error);
        throw error;
    }
}

// SET /////////////////////////////////////////////////////////

//ADMIN
export async function setUserNameAPI(user: User, name: string){

}

//COACH
export async function setSessionCreneauAPI(session: Session, date:Date){

}

export async function getSessionsAPI(): Promise<Session[]> {
    try {
        const response = await api.get<Session[]>("/session");
        return response.data;
    } catch (error) {
        console.error("Error fetching sessions:", error);
        throw error;
    }
}
export async function getUsersAPI(): Promise<User[]> {
    try {
        const response = await api.get<User[]>("/coach/all");
        return response.data;
    } catch (error) {
        console.error("Error fetching users:", error);
        throw error;
    }
}

export async function getCoachsAPI(): Promise<Coach[]> {
    try {
        const response = await api.get<Coach[]>("/coach/all");
        console.log(response);
        return response.data;
    } catch (error) {
        console.error("Error fetching coachs:", error);
        throw error;
    }
}