'use strict';

var ProductListCtrl = ['$scope', 'products', function ($scope, products) {
    $scope.info = products;
}];

ProductListCtrl.resolve = {
    products: ['$q', '$route', 'Product', function ($q, $route, Product) {
        var deferred = $q.defer();

        var successCb = function (result) {
            deferred.resolve(result);
        };

        Product.query({}, successCb);
        return deferred.promise;
    }]
};

var ProductCtrl = ['$scope', '$location', 'product', 'product_groups', function ($scope, $location, product, product_groups) {
    $scope.product = product;
    $scope.product_groups = product_groups;

    $scope.save = function () {
        $scope.product.$save(function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: u.Code});
            $location.path('/Products');
        }, function (data, status) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };

    $scope.delete = function () {
        $scope.product.$delete(function (u, putResponseHeaders) {
            $scope.toasts.push({Type: 'Success', Message: ''});
            $location.path('/Products');
        }, function (data, status) {
            $scope.toasts.push({Type: 'Danger', Message: data.data});
        });
    };
    $('#txtName').focus();
}];

ProductCtrl.resolve = {
    product: ['$q', '$route', 'Product', function ($q, $route, Product) {
        var deferred = $q.defer();

        var id = $route.current.params.id;
        var successCb = function (result) {
            deferred.resolve(result);
        };

        Product.get({id: id}, successCb);
        return deferred.promise;
    }],
    product_groups: ['$q', 'ProductGroup', function ($q, ProductGroup) {
        var deferred = $q.defer();

        var successCb = function (result) {
            deferred.resolve(result);
        };

        ProductGroup.query({}, successCb);
        return deferred.promise;
    }]
};
