from pycnic.core import WSGI, Handler
from key_replacer import KeyReplacer
import requests
import json

class Base(Handler):
    hostname = "https://www.themealdb.com/api/json/v1/1/"

    def __init__(self):
        self.replacable_keys = KeyReplacer(
            [
                ["idMeal", "id"],
                ["strMeal", "name"],
                ["strCategory", "category"],
                ["strArea", "area"],
                ["strInstructions", "instructions"],
                ["strDrinkAlternate", "alternate-drink"],
                ["strMealThumb", "thumbnail-url"],
                ["strTags", "tags"],
                ["strYoutube", "youtube-url"],
                ["strSource", "source-url"],
                ["dateModified", "date-modified"],
            ])

    def normalize(self, response, model_type = "meal"):
        return {
            "data": {
                "id": response["id"],
                "attributes": response,
                "type": model_type,
                }
            }


    def cleanup(self, meal):
        self.replacable_keys.do_replace(meal)
        self.cleanup_instructions(meal)
        self.cleanup_ingredients(meal)

    def cleanup_instructions(self, meal):
        meal["instructions"] = meal["instructions"].replace('\r\n', '\n\n')

    def cleanup_ingredients(self, meal):
        potential_length = 20
        true_length = 0
        # Cleanup Empty Values
        for i in reversed(range(potential_length)):
            x = str(i + 1)
            if (meal["strIngredient" + x] == ''):
                true_length = i
                del meal["strIngredient" + x]
                del meal["strMeasure" + x]

        # Convert Ingredients/Measures to Array of Objects
        meal["ingredients"] = [0]*true_length
        for i in range(0, true_length):
            x = str(i + 1)
            meal["ingredients"][i] = {
                    "name": meal["strIngredient" + x],
                    "measure": meal["strMeasure" + x],
                }
            del meal["strIngredient" + x]
            del meal["strMeasure" + x]

class Details(Base):
    def get(self, meal_id = ''):
        response = json.loads(requests.get(self.hostname + "lookup.php?i=" + meal_id).text)["meals"][0]
        self.cleanup(response)

        return self.normalize(response)


class Random(Base):
    def get(self):
        response = json.loads(requests.get(self.hostname + "random.php").text)["meals"][0]
        self.cleanup(response)

        return self.normalize(response)

class app(WSGI):
    headers = [("Access-Control-Allow-Origin", "*")]
    routes = [
                ("/meals/random", Random()),
                ("/meal/([\w]+)", Details())
            ]
