angular.module('starter.controllers', [])

.controller('SearchCtrl', function($scope, $http, $log, Recipes) {
    Recipes.all().success(function(data) {
        $scope.recipes = data.recipes;
    });
})

.controller('CategoriesCtrl', function($scope, $log, Categories) {
    Categories.all().success(function(data) {
        $scope.categories = data.categories;
    });
})
.controller('CategoryDetailCtrl', function($scope, $log, $stateParams, Recipes) {
    var category = $stateParams.category;
    $scope.category = category;
    $log.debug('Filtering recipes by', category);
    Recipes.all().success(function(data) {
        $scope.recipes = data.recipes;
    });
})

.controller('FavoritesCtrl', function($scope, $http, $log, Recipes) {
    var favoriteRecipes = window.localStorage.getItem('favoriteRecipes') != null ? JSON.parse(window.localStorage.getItem('favoriteRecipes')) : {};

    Recipes.all().success(function(data) {
        var favoritedRecipes = [];
        for (var key in data.recipes) {
            var recipe = data.recipes[key];
            if (favoriteRecipes[recipe.id]) {
                favoritedRecipes.push(recipe);
            }
        }
        $scope.favoritedRecipes = favoritedRecipes;
    });
})

.controller('RecipeDetailCtrl', function($scope, $stateParams, $http, $log) {
    var recipeId = $stateParams.recipeId;
    
    var favoriteRecipes = window.localStorage.getItem('favoriteRecipes') != null ? JSON.parse(window.localStorage.getItem('favoriteRecipes')) : {};
    $scope.favorited = favoriteRecipes[recipeId];
    
    $http({method: 'GET', url: 'indian_recipes.json'})
        .success(function(data, status, headers, config) {
          $log.info('recipes JSON success', data.recipes.length, data.recipes);
          for (idx in data.recipes) {
            if (data.recipes[idx].id == recipeId) {
              $scope.recipe = data.recipes[idx];
              $log.info("Found recipe", $scope.recipe);
              break;
            }
          }
        })
        .error(function(data, status, headers, config) {
          $log.info('recipes JSON error', data);
        });
    
    $scope.favoriteThis = function() {
        $scope.favorited = !$scope.favorited;
        $log.info('favorite', recipeId, '?', $scope.favorited);
        favoriteRecipes[recipeId] = $scope.favorited;
        window.localStorage.setItem('favoriteRecipes', JSON.stringify(favoriteRecipes));
    };

})

.controller('AboutCtrl', function($scope) {
});
