import fetch from "node-fetch";
import config from "../config";
import Session from "../domain/Session";
import SessionRepository from "../domain/SessionRepository";
import Action from "../domain/Action";

const SessionURL: string = `http://${config.session.host}:${config.session.port}/session/`;

export default class SessionRepositoryREST implements SessionRepository {
    public webSiteName: string;

    public findSessionById(sessionId: string): Promise<Session> {
        const sessionFetch: string = SessionURL + sessionId;
        return fetch(sessionFetch)
            .then( (response) => {
                if (response.ok) {
                    return response.json();
                } else {
                    return Promise.reject("findSessionSite REST error");
                }
            })
            .then( sessionData => {
                let session = new Session(sessionData.id);
                sessionData.explorationList.forEach((explorationData) => {
                    const explorationNumber: number = session.startExploration();
                    const actionList = []
                    explorationData.interactionList
                        .sort( (interA, interB) => interA.index - interB.index)
                        .forEach((interaction) => {
                            if (interaction.concreteType === "Action") {
                                actionList.push(new Action(interaction.kind, interaction.value));
                            }
                        
                        });
                    session.addActionListToExploration(explorationNumber, actionList);
                });
                return session;
            });
    }

}
