import flask
from flask import Blueprint
from flask import request, jsonify


from config import Config as cfg
from app.main.engine.enum.StatusEnum import StatusEnum
from app.main.engine.service.EngineService import EngineService


class MainController:

    def __init__(self, app: flask.Flask) -> None:
        self.blueprint = Blueprint('css_engine_blueprint', __name__, url_prefix='')
        self.app = app
        self.max_executions = cfg.max_engine_threads
        self.executions = 0

    def get_blueprint(self):
        return self.blueprint

    def blueprints(self):

        @self.blueprint.route('/api/engine/action', methods=['POST'])
        def parser():
            """ Method to apply an action trhough script execution and save the results in db
            Parameters:
                descriptor (dict) : From body. Dictionary who have all the attributes and rules to get new attributes (if is neccesary)
                                                and validators
                response (dict) : The result message with status and his description
            """
            response = {}
            try:
                self.executions += 1
                descriptor = request.get_json()
                service = EngineService(self.app, descriptor, self.executions, self.max_executions)
                response = service.run()
                self.app.logger.info(response)
            except Exception as e:
                self.app.logger.error(f"Error en el envío del parser al servicio. {e}")
                response["statusCode"] = StatusEnum.ERROR.name
                response["error"] = {"message": "", "detail": str(e)}
            finally:
                self.executions -= 1
                return jsonify(response)
