import ObjectiveService from "../application/SequenceEvaluationApplication";

const ERROR_STATUS: number = 500;
const SUCCESS_STATUS: number = 200;

export default function attachRoutes(app, evaluatorService: ObjectiveService): void {

    app.get("/evaluator/ping", (req, res) => {
        res.send("alive");
    });

    app.get("/evaluator/getEvaluator/:webSiteId", (req, res) => {
        const { webSiteId } = req.params;
        evaluatorService.getSequenceEvaluator(webSiteId).then((evaluator) => {
            if (!evaluator) {
                return res.status(204).send(null);
            }
            return res.send({
                stepList: evaluator.stepList.map(step => ({
                    name: step.name, 
                    expression: step.expression
                }))
            });
        }).catch((error) => {
            console.error(error);
            return res.status(ERROR_STATUS).send(error);
        });
    });

    app.post("/evaluator/create", (req, res) => {
        const { webSiteId, stepList } = req.body;
        console.log("create", req.body)
        evaluatorService.createSequenceEvaluator(webSiteId, stepList).then(() => {
            return res.sendStatus(SUCCESS_STATUS);
        }).catch((error) => {
            console.error(error);
            return res.status(ERROR_STATUS).send(error);
        });
    });

    app.post("/evaluator/update", (req, res) => {
        const { webSiteId, stepList } = req.body;
        console.log("update", req.body)

        evaluatorService.updateSequenceEvaluator(webSiteId, stepList).then(() => {
            return res.sendStatus(SUCCESS_STATUS);
        }).catch((error) => {
            console.error(error);
            return res.status(ERROR_STATUS).send(error);
        });
    });

    app.post("/evaluator/evaluateSequence", (req, res) => {
        const { webSiteId, interactionList } = req.body;
        evaluatorService.evaluateSequence(webSiteId, interactionList).then((evaluation) => {
            console.log(evaluation);
            return res.status(SUCCESS_STATUS).send({evaluation});
        }).catch((error) => {
            console.error(error);
            return res.status(ERROR_STATUS).send(error);
        });
    });

}
