/*global angular*/
(function () {
    angular
        .module('simplAdmin.wooCommerce')
        .controller('WooProductListCtrl', ['wooCommerceService', 'translateService', WooProductListCtrl]);

    function WooProductListCtrl(wooCommerceService, translateService) {
        var vm = this;
        vm.tableStateRef = {};
        vm.products = [];
        vm.translate = translateService;
        vm.isEditMode = false;

        vm.getProducts = function getProducts(tableState) {
            vm.tableStateRef = tableState;
            vm.isLoading = true;
            wooCommerceService.getProducts(tableState).then(function (result) {
                vm.products = result.data.items;
                tableState.pagination.numberOfPages = result.data.numberOfPages;
                tableState.pagination.totalItemCount = result.data.totalRecord;
                vm.isLoading = false;
            });
        };

        vm.save = function save(product) {
            var promise;
            if (vm.isEditMode) {
                promise = wooCommerceService.editProduct(product);
            } else {
                promise = wooCommerceService.createProduct(product);
            }

            promise
                .then(function (result) {
                    toastr.success("Product save success!");
                })
                .catch(function (response) {
                    var error = response.data;
                    toastr.error(error);
                });
        };

        vm.deleteProduct = function deleteProduct(product) {
            bootbox.confirm('Are you sure you want to delete this product: ' + simplUtil.escapeHtml(product.name), function (result) {
                if (result) {
                    wooCommerceService.deleteProduct(product)
                        .then(function (result) {
                            vm.getProducts(vm.tableStateRef);
                            toastr.success(product.name + ' has been deleted');
                        })
                        .catch(function (response) {
                            toastr.error(response.data.error);
                        });
                }
            });
        };
    }
})();
