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";
import { useLocalData } from "./context/useLocalData";

//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 loginOrRegister(keycloak:Keycloak): Promise<User|null>{
    try {
        if(keycloak.tokenParsed!=null){
        const roles = keycloak.tokenParsed?.realm_access?.roles
        if(roles!=null){
            if(roles.includes("admin")){
                const newAdmin: Admin = new Admin();
                newAdmin.keycloakId = keycloak.tokenParsed.sub || "";
                newAdmin.email = keycloak.tokenParsed.email || "";
                newAdmin.nom = keycloak.tokenParsed.family_name || "";
                newAdmin.prenom = keycloak.tokenParsed.given_name || "";
                const response = await athleteService.create(newAdmin.toDTO());
                const admin = new Admin(response.data);
                return admin;
            }
            else if(roles.includes("coach")){
                const newCoach: Coach = new Coach();
                newCoach.keycloakId = keycloak.tokenParsed.sub || "";
                newCoach.email = keycloak.tokenParsed.email || "";
                newCoach.nom = keycloak.tokenParsed.family_name || "";
                newCoach.prenom = keycloak.tokenParsed.given_name || "";
                const response = await coachService.create(newCoach.toDTO());
                const coach = new Coach(response.data);
                return coach;

            }
            else if(roles.includes("athlete")){
                const newAthlete: Athlete = new Athlete();
                newAthlete.keycloakId = keycloak.tokenParsed.sub || "";
                newAthlete.email = keycloak.tokenParsed.email || "";
                newAthlete.nom = keycloak.tokenParsed.family_name || "";
                newAthlete.prenom = keycloak.tokenParsed.given_name || "";
                const response = await athleteService.create(newAthlete.toDTO());
                const athlete = new Athlete(response.data);
                return athlete;
            }
                else console.error("Error : role inconnu");
            }
            else console.error("Error : role null");
        }
        else console.error("Error : token Keylcoak null");
        console.error("Error : pendant la récupération de l'User");
        return null;
    }
    catch (error) {
        console.error("Error fetching user:", error);
        return null;
    }   
}

export async function updateActivitiesOfSessionAPI(session:Session,activities:Activite[]){
    try {
        const session_id = session.id
        for (const activity of activities) {
            const response = await activiteService.update(activity.id!, activity.toDTO());
        }
        // To refresh the activities in the session object
        const response = await sessionService.getActivities(session_id!);
        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 {
        const session_id =session.id
        const user_id = user.id
        const response = await sessionService.subscribe(session_id!, user_id!);
        return true;
    } catch (error) {
        console.error("Error subscribing to session:", error);
        return false;
    }
}

export async function unsubscribeSessionAPI(user:User, session:Session):Promise<boolean>{
    try {
        const session_id =session.id
        const user_id = user.id
        const response = await sessionService.unsubscribe(session_id!, user_id!);
        return true;
    } catch (error) {
        console.error("Error unsubscribing from session:", error);
        return false;
    }
}



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

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


export async function createActivityAPI(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);
        console.log(response);
        return 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;
    }
}

// SET /////////////////////////////////////////////////////////
export async function createAdminAPI(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;
    }
}

//GET /////////////////////////////////////////////////////////

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

//SESSION
export async function getSessionsOfUserAPI(user:Coach|Athlete){
    try {
        if (user instanceof Coach) {
            const response = await coachService.getSessionsForCoach(user.id); //TODO
            return response.data;
        }else if (user instanceof Athlete) {
            const response = await athleteService.getSessionsForAthlete(user.id); //TODO
            return response.data;
        }
    }catch (error) {
        console.error("Error fetching sessions for user:", error);
        return [];
    }
}

export async function getAllSessionsAPI():Promise<Session[]>{
    try {
        const response = await sessionService.getAll();
        return response.data;
    } catch (error) {
        console.error("Error fetching sessions:", error);
        throw error;
    }
}

//COACH
export async function getAllCoach(): 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;
    }
}

//ATHLETE
export async function getAllAthlete(): Promise<Athlete[]> {
    try {
        const response = await athleteService.getAll();
        return response.data;
    } catch (error) {
        console.error("Error fetching users:", error);
        throw error;
    }
}

