import CSP_Model from "../domain/ModelContiguousSequentialPattern";
import ModelRepository from "../domain/ModelRepository";
import ModelSchema from "./ModelSchema";

export default class ModelRepositoryMongo implements ModelRepository {

    public addModel(model: CSP_Model): Promise<string> {
        return ModelSchema.create({
                _id: model.id,
                depth: model.depth,
                interpolationfactor: model.interpolationfactor,
                sessionIdList: model.getLinkedSessionIdList(),
            })
            .then( () => {
                return model.id;
            });
    }

    public findModelById(modelId: string): Promise<CSP_Model> {
        return ModelSchema.findOne({_id: modelId}).lean().exec()
            .then((modelData: any) => {
                if (!modelData) {
                    return null;
                }
                const model = new CSP_Model(modelData.depth, modelData.interpolationfactor, modelId);
                modelData.sessionIdList.forEach((sessionId) => {
                    model.linkWithSession(sessionId);
                });
                return model;
            });
    }

    public addSessionToModel(modelId: string, sessionId: string): Promise<void>  {
        return ModelSchema.findOne({_id: modelId}).then((model: any) => {
                model.sessionIdList.push(sessionId);
                return model.save();
            }).then(() => {
                return;
            });
    }
}
