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

    function WooProductFormCtrl($state, $stateParams, wooCommerceService, translateService) {
        var vm = this;
        vm.translate = translateService;
        vm.product = {};
        vm.productId = $stateParams.id;
        vm.isEditMode = vm.productId > 0;

        vm.updateSlug = function () {
            vm.product.slug = slugify(vm.product.name);
        };

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

            promise
                .then(function (result) {
                    $state.go('wc-products');
                })
                .catch(function (response) {
                    var error = response.data;
                    vm.validationErrors = [];
                    if (error && angular.isObject(error)) {
                        for (var key in error) {
                            vm.validationErrors.push(error[key][0]);
                        }
                    } else {
                        vm.validationErrors.push('Could not add product.');
                    }
                });
        };

        function init() {
            if (vm.isEditMode) {
                wooCommerceService.getProduct(vm.productId).then(function (result) {
                    vm.product = result.data;
                });
            }
        }

        init();
    }
})();
