def getShoppingList(name=None):

    """ It searches a shopping list by name or finds the latest saved"""

    shop_list = ''
    all_names = ''
    i_list = {}
    date_created = ''

    if 'User' in session:

        if name:

            shop_list = ShoppingList.getShoppingListByName(name, session['User'])
            
        else:

            shop_list = ShoppingList.getLatestShoppingList(session['User'])
            if shop_list:
                name = shop_list[0].list_name
        

        if len(shop_list) > 0:

            date_created = shop_list[0].date_created

            all_names = ShoppingList.getShoppingListNames(session['User'])

            i_list = helpFunctions.makeShoppingList(shop_list)


        return render_template("view_shopping_list.html", list=i_list,
                    names=all_names, date_created=date_created, name=name )

    else:

        flash = []
        flash = "You need to login"
        return render_template("/error.html", url="/getShoppingLists")
def sendShoppingList():

    """ It sends the shopping list by SMS with Twilio API """

    from twilio.rest import TwilioRestClient
 
    client = TwilioRestClient()

    name = request.form.get('listIng')

    # It finds the shopping list by name and creates a dictionary of ingredients
    #  and aisle
    if 'User' in session:
    
        shop_list = ShoppingList.getShoppingListByName(name, session['User'])
        i_list = helpFunctions.makeShoppingList(shop_list)

    else:

        flash = []
        flash = "You need to login"
        return render_template("/error.html", url="homepage.html")
    
    message = ''

    # It creates a string message with all the ingredients and aisles

    for aisle in i_list:
        
        message += '\n'+aisle.upper() + ':\n'

        message += '\n'.join(i_list[aisle])


    message = client.messages.create(to="+14156018298", from_="+16506810994",
                                     body=message)    

    return  redirect("/getShoppingLists")