def post_ingredients():
    """
        "POST": registrar un ingrediente
    """
    request_body = request.json

    if request_body is None:
        return jsonify({"response": "empty body"}), 400

    if ("name" not in request_body or "category" not in request_body):
        return jsonify({"result": "missing fields in request body"}), 400

    if (request_body["name"] == "" or request_body["category"] == ""):
        return jsonify({"response": "empty property values"}), 400

    new_ingredient = Ingredient.register(
        request_body["name"],
        request_body["category"],
    )
    db.session.add(new_ingredient)
    try:
        db.session.commit()
        return jsonify(new_ingredient.serializeIngredient()), 201
    except Exception as error:
        db.session.rollback()
        print(f"{error.args} {type(error)}")
        return jsonify({"response": f"{error.args}"}), 500
def post_recipe():
    """
        "POST": registrar una receta y devolverla
    """
    body = request.json
    if body is None:
        return jsonify({"response": "empty body"}), 400

    if ("description" not in body or "name" not in body
            or "instructions" not in body or "tags" not in body
            or "img_url" not in body):
        return jsonify({"response": "Missing properties"}), 400
    if (body["description"] == "" or body["name"] == ""
            or body["instructions"] == "" or body["tags"] == ""
            or body["img_url"] == ""):
        return jsonify({"response": "empty property values"}), 400

    obtained_ingredients_id = []
    ingredients_body = []
    ingredients_body = body["ingredients"]
    #ingredients_body = literal_eval(ingredients_body)

    #print(type (ingredients_body))
    # Converting string to list
    #ingredients_body = ingredients_body.strip('][').split(', ')

    recipe = []
    for individual_ingredient in ingredients_body:

        #print(f'este es el for individdual {individual_ingredient}')
        #recipe.append(new_recipe_id)
        category = "a"
        match = db.session.query(
            Ingredient.name).filter_by(name=individual_ingredient).first()
        #print(f'esto sería el match {match} y el ingredient {individual_ingredient}')
        ######
        just_ingredient = individual_ingredient.replace('\'', "\"")
        new_ingredient = Ingredient.register(just_ingredient, "none", recipe)
        db.session.add(new_ingredient)
        try:
            db.session.commit()
        except Exception as error:
            db.session.rollback()
    ################################Hasta este punto está funcionando

    #print(type (ingredients_body))
    for individual_ingredient in ingredients_body:
        #print(type (individual_ingredient))
        #print(individual_ingredient)
        just_ingredient = individual_ingredient.replace('\'', "\"")
        #Para obtener el id del ingrediente si el nombre del mismo aparece en el body
        match = db.session.query(
            Ingredient.id).filter_by(name=just_ingredient).first()
        #print(f'esto sería el match {match}')
        #print(type(match))
        obtained_ingredients_id.append(match)
        #con el ejemplo los ID obtenidos vienen como listas, pero siguiente formato [(1,),(2,)], hay que arregarlo

    #print(f'esta sería obtained_id {obtained_ingredients_id}')
    #print(type(obtained_ingredients_id))
    string_ingredient_id = "".join(map(str, obtained_ingredients_id))
    #print(f'esta sería como cadena{string_ingredient_id}')
    string_ingredient_id = string_ingredient_id.strip('()')
    string_ingredient_id = string_ingredient_id.replace(')(', "")
    string_ingredient_id = string_ingredient_id.replace(')', "")
    if (string_ingredient_id[-1] == ","):
        string_ingredient_id = string_ingredient_id.rstrip(
            string_ingredient_id[-1])
    #print(f'esta sería como cadena recortada {string_ingredient_id}') ##en este punto los id quedan: 1,2
    string_ingredient_id = "[" + string_ingredient_id + "]"
    #print(f'esta sería como cadena string {string_ingredient_id}') ##en este punto los id quedan [1,2] pero strings
    #string_ingredient_id = list(map(int, string_ingredient_id))
    #print(f'línea 378 {string_ingredient_id}')
    string_ingredient_id = literal_eval(str(string_ingredient_id))
    #print(f'esta sería como lista enteros {string_ingredient_id}') ##en este punto devuelve como lista de enteros
    #print(type(string_ingredient_id))
    #print(body["ingredients"])
    body[
        "ingredients"] = string_ingredient_id  ####hasta aquí está bien, devolvió lista id de onion y potato

    #ya teniendo la lista de los ID de los ingredientes, faltaría el ID del recipe que estamos por crear, para
    #meterlo en la tabla relacional, y después de eso, poder registrar el Recipe correctamente.
    if (db.session.query(Recipe).order_by(Recipe.id.desc()).first()):
        last_recipe_id = db.session.query(Recipe).order_by(
            Recipe.id.desc()).first()
        last_recipe_id = (last_recipe_id.id)
        new_recipe_id = 1 + last_recipe_id
    else:
        last_recipe_id = 0
        new_recipe_id = 1
    # #print(f'Este es el último id registrado {last_recipe_id}') #devuelve <Recipe 1>
    # #print(type(last_recipe_id)) #es del tipo models.Recipe
    # last_recipe_id=(last_recipe_id.id)
    # #print(f'Este es el último id registrado {last_recipe_id}')
    # #print(type(last_recipe_id)) #es del tipo entero!!
    # new_recipe_id = 1+last_recipe_id
    # #print(new_recipe_id)

    #Suponemos que del body llega una lista [onion, potato] de ingredientes, tal que:
    #ingredients_body = body["ingredients"]
    ####################################################################################

    ##Ya teniendo el ID del nuevo recipe a crear y la lista de ID de ingredientes, es hora de registrar en
    ## la tabla de clase relaciona Recipeingredients
    integer_ingredient_id = string_ingredient_id  # it's a List
    #print(f'This is integer_ingredient_id {integer_ingredient_id} and type:')
    #print(type(integer_ingredient_id))

    empty_list = []
    ##Registro del nuevo Recipe
    new_list_ingredients = []
    new_recipe = Recipe.register(
        body["name"],
        body["description"],
        body["date_published"],
        body["instructions"],
        body["tags"],
        #body["price"],
        #body["score"],
        body["img_url"],
        empty_list,  #but integer or may be sqlalchemy object
        list_to_string(ingredients_body))
    db.session.add(new_recipe)
    db.session.commit()

    recipe_id_list = []
    ingredients_list = []

    #Registro clase intermedia Recipeingredients######################################
    for counter in integer_ingredient_id:
        new_relationship = Recipeingredients.register(counter, new_recipe_id)
        print(counter)
        db.session.add(new_relationship)
        db.session.commit()
    try:
        #db.session.commit()
        recipes = db.session.query(Recipe).filter_by(id=new_recipe_id).all()
        recipes_serialize = list(
            map(
                lambda recipe: recipe.serializeFinal(
                    new_recipe_id, list_to_string(ingredients_body)), recipes))
        return jsonify(recipes_serialize), 200

        #final_recipe_json = show_recipe_json(new_recipe_id, ingredients_body)
        #return final_recipe_json, 200
    except Exception as error:
        db.session.rollback()
        print(f"{error.args} {type(error)}")
        return jsonify({"response": f"error en tabla relacional"}), 500