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

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

const STATUS_REPONSE_IS_NULL = 204;
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(STATUS_REPONSE_IS_NULL).send(null);
            }
            return res.send(evaluator);
        }).catch((error) => {
            console.error(error);
            return res.status(ERROR_STATUS).send(error);
        });
    });

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

        evaluatorService.createSequenceEvaluator(webSiteId, description, 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, description, stepList } = req.body;
        console.log(req.body)

        evaluatorService.updateSequenceEvaluator(webSiteId, description, 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) => {
            return res.status(SUCCESS_STATUS).send({evaluation});
        }).catch((error) => {
            console.error(error);
            return res.status(ERROR_STATUS).send(error);
        });
    });

    app.post("/evaluator/expressionToDot", (req, res) => {
        const { expression } = req.body;
        evaluatorService.checkExpressionValidity(expression).then(expressionIsValid => {
            if (!expressionIsValid) {
                return res.status(SUCCESS_STATUS).send({
                    expressionIsValid: false,
                    dot: undefined
                })
            } else {
                evaluatorService.expressionToDot(expression).then((dot) => {
                    return res.status(SUCCESS_STATUS).send({
                        expressionIsValid: true,
                        dot
                    })
                })
            }
        }).catch((error) => {
            console.error(error);
            return res.status(ERROR_STATUS).send(error);
        });
    })

}
