<commit_before>/**
 * Created by NetHunter on 2015. 12. 17..
 */
(function () {
  'use strict';

  angular
    .module('app')
    .controller('CartModalController', CartModalController);

  CartModalController.$inject = ['$uibModalInstance', 'cartService', 'uibDatepickerConfig', '$log', 'modalService', '$rootScope', 'firebaseService', '$filter', 'authenticator'];

  /* @ngInject */
  function CartModalController($uibModalInstance, cartService, uibDatepickerConfig, $log, modalService, $rootScope, firebaseService, $filter, authenticator) {
    var vm = this;
    var date = new Date();
    var ingredients;
    var stock;
    var allowToOrder;

    activate();

    ////////////////

    function activate() {
      setup();
      vm.close = closeModal;
      vm.products = cartService.getCart();
      vm.removeOne = removeOneItem;
      vm.addOne = addOneItem;
      vm.remove = removeItem;
      vm.pickUps = getPickUps();
      vm.checkout = checkout;
      vm.getTotal = totalPrice;
      vm.deliveryDate = date;
      vm.openCalendar = openCalendar;
      vm.isCalendarOpened = false;
      vm.deliveryTime = date;
      $rootScope.$on('notification.closed', finishShopping);
    }

    function checkout() {
      var msg;
      getIngredients();
      getStock().then(function () {
        hasEnoughIngredients();
        if (allowToOrder) {
          var amount;
          angular.forEach(ingredients, function (ingredient) {
            amount = ingredient.quantity;
            angular.forEach(stock, function (item) {
              if (item.ingredientId === ingredient.ingredientId) {
                firebaseService.getObject('/stock/' + item.$id).$loaded().then(function (stockItem) {
                  if (stockItem.quantity <= amount) {
                    amount -= stockItem.quantity;
                    stockItem.$remove();
                  } else {
                    stockItem.quantity -= amount;
                    stockItem.$save();
                    return true;
                  }
                });
              }
            });
          });
          msg = 'Sikeres vásárlás!';
          saveOrder();
          $log.info('OMG he is going for it!!!! For real real, not just for play play.');
        } else {
          msg = 'Sikertelen vásárlás!';
        }
        modalService.show('scripts/product/cart/modal/notification.template.html', 'CartNotificationController', 'sm', {message: msg});
      });
    }

    function getPickUps() {
      return [
        {city: 'Budapest'},
        {city: 'Debrecen'},
        {city: 'Szeged'},
        {city: 'Sopron'},
        {city: 'Pécs'},
        {city: 'Békéscsaba'}
      ];

    }

    function saveOrder(){
      var products = [];
      angular.forEach(vm.products, function(prod){
        products.push({productId: prod.id, quantity: prod.amount});
      });
      var order = {deliveryDate: vm.deliveryDate.toISOString(), products: products, timestamp: new Date().toISOString(), userId: authenticator.currentUser().uid};
      firebaseService.saveObject('/orders', order);
    }
    function removeOneItem(product) {
      cartService.removeOne(product);
    }

    function addOneItem(product) {
      cartService.addOne(product);
    }

    function removeItem(product) {
      cartService.remove(product);
    }

    function closeModal() {
      $uibModalInstance.close();
      $log.info('Cart modal has been closed.');
    }

    function totalPrice() {
      var total = 0;
      angular.forEach(vm.products, function (product) {
        total += product.price * product.amount;
      });
      return total;
    }

    function openCalendar() {
      vm.isCalendarOpened = true;
      $log.info('Calendar has been opened.');
    }

    function finishShopping(event, data) {
      if (data) {
        cartService.clear();
      }
      closeModal();
    }

    function setup() {
      if (date.getHours() >= 12) {
        date.setDate(date.getDate() + 1);
      }
      uibDatepickerConfig.minDate = date;
    }

    function hasEnoughIngredients() {
      var stockItem;
      allowToOrder = true;
      var result = getStockSum();
      angular.forEach(ingredients, function (ingredient) {
        stockItem = $filter('filter')(result, function (item) {
          return item.ingredientId === ingredient.ingredientId;
        });

        if (stockItem.length == 0 || stockItem[0].quantity < ingredient.quantity) {
          allowToOrder = false;
          return allowToOrder;
        }
      });
    }

    function getIngredients() {
      ingredients = [];
      var ingredient;

      angular.forEach(vm.products, function (product) {
        angular.forEach(product.ingredients, function (item) {
          ingredient = $filter('filter')(ingredients, function (ing) {
            return ing.ingredientId === item.ingredientId;
          });
          item.quantity *= product.amount;
          if (ingredient.length == 0) {
            ingredients.push(item);
          } else {
            ingredient[0].quantity += item.quantity;
          }
        });
      });
    }

    function getStockSum() {<commit_msg>fixing some bugs<commit_after>/**
 * Created by NetHunter on 2015. 12. 17..
 */
(function () {
  'use strict';

  angular
    .module('app')
    .controller('CartModalController', CartModalController);

  CartModalController.$inject = ['$uibModalInstance', 'cartService', 'uibDatepickerConfig', '$log', 'modalService', '$rootScope', 'firebaseService', '$filter', 'authenticator'];

  /* @ngInject */
  function CartModalController($uibModalInstance, cartService, uibDatepickerConfig, $log, modalService, $rootScope, firebaseService, $filter, authenticator) {
    var vm = this;
    var date = new Date();
    var ingredients;
    var stock;

    activate();

    ////////////////

    function activate() {
      setup();
      vm.close = closeModal;
      vm.products = cartService.getCart();
      vm.removeOne = removeOneItem;
      vm.addOne = addOneItem;
      vm.remove = removeItem;
      vm.pickUps = getPickUps();
      vm.checkout = checkout;
      vm.getTotal = totalPrice;
      vm.deliveryDate = date;
      vm.openCalendar = openCalendar;
      vm.isCalendarOpened = false;
      vm.deliveryTime = date;
      $rootScope.$on('notification.closed', finishShopping);
    }

    function checkout() {
      var msg;
      getIngredients();
      getStock().then(function () {
        if (hasEnoughIngredients()) {
          var amount;
          angular.forEach(ingredients, function (ingredient) {
            amount = ingredient.quantity;
            angular.forEach(stock, function (item) {
              if (item.ingredientId === ingredient.ingredientId) {
                firebaseService.getObject('/stock/' + item.$id).$loaded().then(function (stockItem) {
                  if (stockItem.quantity <= amount) {
                    amount -= stockItem.quantity;
                    stockItem.$remove();
                  } else {
                    stockItem.quantity -= amount;
                    stockItem.$save();
                    return true;
                  }
                });
              }
            });
          });
          msg = 'Sikeres vásárlás!';
          saveOrder();
          $log.info('OMG he is going for it!!!! For real real, not just for play play.');
        } else {
          msg = 'Sikertelen vásárlás!';
        }
        modalService.show('scripts/product/cart/modal/notification.template.html', 'CartNotificationController', 'sm', {message: msg});
      });
    }

    function getPickUps() {
      return [
        {city: 'Budapest'},
        {city: 'Debrecen'},
        {city: 'Szeged'},
        {city: 'Sopron'},
        {city: 'Pécs'},
        {city: 'Békéscsaba'}
      ];

    }

    function saveOrder() {
      var products = [];
      angular.forEach(vm.products, function (prod) {
        products.push({productId: prod.id, quantity: prod.amount});
      });
      var order = {
        deliveryDate: vm.deliveryDate.toISOString(),
        products: products,
        timestamp: new Date().toISOString(),
        userId: authenticator.currentUser().uid
      };
      $log.info('Saving order.', order);
      firebaseService.saveObject('/orders', order);
    }

    function removeOneItem(product) {
      cartService.removeOne(product);
    }

    function addOneItem(product) {
      cartService.addOne(product);
    }

    function removeItem(product) {
      cartService.remove(product);
    }

    function closeModal() {
      $uibModalInstance.close();
      $log.info('Cart modal has been closed.');
    }

    function totalPrice() {
      var total = 0;
      angular.forEach(vm.products, function (product) {
        total += product.price * product.amount;
      });
      return total;
    }

    function openCalendar() {
      vm.isCalendarOpened = true;
      $log.info('Calendar has been opened.');
    }

    function finishShopping(event, data) {
      if (data) {
        cartService.clear();
      }
      closeModal();
    }

    function setup() {
      if (date.getHours() >= 12) {
        date.setDate(date.getDate() + 1);
      }
      uibDatepickerConfig.minDate = date;
    }

    function hasEnoughIngredients() {
      var stockItem;
      var allowToOrder = true;
      var result = getStockSum();
      console.log(result);
      console.log(ingredients);
      angular.forEach(ingredients, function (ingredient) {
        stockItem = $filter('filter')(result, function (item) {
          return item.ingredientId === ingredient.ingredientId;
        });

        if (stockItem.length == 0 || stockItem[0].quantity < ingredient.quantity) {
          allowToOrder = false;
          return allowToOrder;
        }
      });
      return allowToOrder;
    }

    function getIngredients() {
      ingredients = [];
      var ingredient;
      var array = angular.copy(vm.products);
      angular.forEach(array, function (product) {
        angular.forEach(product.ingredients, function (item) {
          ingredient = $filter('filter')(ingredients, function (ing) {
            return ing.ingredientId === item.ingredientId;
          });
          item.quantity *= product.amount;
          if (ingredient.length == 0) {
            ingredients.push(item);
          } else {
            ingredient[0].quantity += item.quantity;
          }
        });
      });
    }

    function getStockSum() {
{'fraction_non_alphanumeric': 0.13363392171910976, 'fraction_numerical': 0.0030698388334612432, 'mean_word_length': 2.0989892984542213, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4247528', 'n_tokens_mistral': 3048, 'n_tokens_neox': 2905, 'n_words': 595}