(function () {
    angular
        .module('simpl.shoppingCart', [])
        .controller('shoppingCartListCtrl', [
            '$scope', '$q',
            'shoppingCartService',
            function ($scope, $q, shoppingCartService) {
                var vm = this;
                vm.cart = {};
                vm.addingProduct = {};
                vm.products = [];
                vm.filterProduct = {};
                vm.customer = { id: 20, fullName: 'Guest' };
                vm.searchedCustomers = [];
                vm.isLoading = false;
                vm.productTable = {
                    pagination: { }
                };
                vm.cartTable = {
                    pagination: {}
                };
                vm.order = { id: 0 };
                vm.isSubmit = false;
                vm.isCreatedOrder = false;

                function cartDataCallback(result) {
                    if (result.data.error) {
                        toastr.error(result.data.message);
                    }
                    else {
                        vm.cart = result.data;
                        vm.customer.fullName = vm.cart.customerName;
                        vm.cartTable.pagination.totalItemCount = vm.cart.items.length;
                    }
                }

                function getShoppingCartItems() {
                    shoppingCartService.getShoppingCartItems().then(cartDataCallback).catch(function (err) { console.log(err) });
                }

                vm.getCart = function () {
                    shoppingCartService.getCart(vm.customer.id).then(cartDataCallback).catch(function (err) { console.log(err) });
                };

                vm.updateTaxAndShippingPrice = function updateTaxAndShippingPrice() {
                    if (vm.selectedShippingAddressId === '0' && !vm.shippingAddress.stateOrProvinceId) {
                        vm.shippingOptions = [];
                        return;
                    }
                    if (!vm.cart || !vm.cart.id) {
                        return;
                    }
                    shoppingCartService.updateTaxAndShippingPrice(
                        vm.cart.id,
                        {
                            existingShippingAddressId: vm.selectedShippingAddressId,
                            newShippingAddress: vm.shippingAddress,
                            selectedShippingMethodName: vm.selectedShippingOption
                        }
                    ).then(function (result) {
                        vm.shippingOptions = result.data.shippingPrices;
                        vm.cart = result.data.cart;
                        if (vm.shippingOptions.length === 0) {
                            toastr.error("Sorry, this items can't be shipped to your selected address");
                        } else {
                            vm.selectedShippingOption = result.data.selectedShippingMethodName;
                        }
                    });
                };

                vm.removeShoppingCartItem = function removeShoppingCartItem(item) {
                    //shoppingCartService.removeShoppingCartItem(item.id).then(cartDataCallback);
                    shoppingCartService.removeCartItem(item.id).then(function (result) {
                        vm.getCart();
                    });
                };

                vm.increaseQuantity = function increaseQuantity(item) {
                    //shoppingCartService.updateQuantity(item.id, item.quantity + 1 ).then(cartDataCallback);
                    item.quantity = item.quantity + 1;
                    shoppingCartService.updateCartItem(item).then(function (result) {
                        vm.getCart();
                    });
                };

                vm.decreaseQuantity = function decreaseQuantity(item) {
                    if (item.quantity <= 1) {
                        return;
                    }
                    item.quantity = item.quantity - 1;
                    shoppingCartService.updateCartItem(item).then(function (result) {
                        vm.getCart();
                    });
                };

                vm.updateCartItemQuantity = function (item) {
                    shoppingCartService.updateCartItem(item).then(function (result) {
                        vm.getCart();
                    });
                };

                vm.removeCartItem = function (item) {
                    shoppingCartService.removeCartItem(item.id).then(function (result) {
                        vm.getCart();
                    });
                };

                vm.applyCoupon = function applyCoupon() {
                    vm.couponErrorMessage = '';
                    shoppingCartService.applyCoupon(vm.couponCode).then(function (result) {
                        if (result.data.succeeded === false) {
                            vm.cart.couponValidationErrorMessage = result.data.errorMessage;
                        } else {
                            cartDataCallback(result);
                        }
                    });
                };

                vm.saveOrderNote = function saveOrderNote() {
                    shoppingCartService.saveOrderNote(vm.cart.orderNote).then(function () {
                        toastr.success('Order note has been saved');
                    });
                };

                vm.unlock = function unlock() {
                    shoppingCartService.unlock().then(function () {
                        toastr.success('Cart unlocked');
                        vm.cart.lockedOnCheckout = false;
                    });
                };

                vm.getProducts = function getProducts() {
                    vm.filterProduct.name = '';
                    vm.isLoading = true;
                    shoppingCartService.getProducts(vm.filterProduct).then(function (result) {
                        vm.products = result.data.items;
                        vm.productTable.pagination.numberOfPages = result.data.numberOfPages;
                        vm.productTable.pagination.totalItemCount = result.data.totalRecord;
                        vm.isLoading = false;
                    });
                };

                vm.selectProduct = function (product) {
                    vm.addingProduct = product;
                    vm.isSearchingProducts = false;
                    vm.addProduct();
                };

                vm.enterProductId = function (keyEvent) {
                    if (keyEvent.which === 13) {
                        vm.isSearchingProducts = true;
                        shoppingCartService.quickCheckProduct(vm.addingProduct.id).then(function (result) {
                            vm.isSearchingProducts = false;
                            vm.addProduct();
                        }).catch(function (response) {
                            toastr.error(response.data.error);
                        });

                        keyEvent.preventDefault();
                    }
                }

                vm.addProduct = function () {
                    if (!vm.addingProduct.id) {
                        toastr.error("Product not found");
                        return;
                    }

                    var cartItem = {
                        productId: vm.addingProduct.id,
                        quantity: 1
                    };

                    shoppingCartService.addCartItem(vm.customer.id, cartItem).then(function () {
                        //getShoppingCartItems();
                        vm.getCart();
                        vm.addingProduct = {};
                        vm.isCreatedOrder = false;
                    });
                };

                vm.searchProducts = function () {
                    vm.isSearchingProducts = true;
                    var params = {
                        name: vm.addingProduct.name,
                    };
                    shoppingCartService.quickSearchProducts(params).then(function (result) {
                        vm.products = result.data.items;
                    });
                };

                vm.createOrder = function createOrder() {
                    if (vm.selectedShippingAddressId === 0) {
                        toastr.error("Sorry, please select or input shipping address first!");
                        return;
                    }

                    if (vm.isSubmit) {
                        return;
                    }
                    vm.isSubmit = true;

                    shoppingCartService.createOrder(
                        vm.cart.id,
                        {
                            shippingMethod: 'Free',
                            shippingAddressId: vm.selectedShippingAddressId,
                            newAddressForm: vm.shippingAddress,
                            orderNote: vm.cart.orderNote,
                            useShippingAddressAsBillingAddress: true
                        }
                    ).then(function (result) {
                        if (result.data.error) {
                            toastr.error(result.data.message);
                        }
                        else {
                            toastr.success("Order created");
                            vm.order = result.data;
                            vm.isCreatedOrder = true;

                            vm.getProducts();
                            vm.resetCart();
                        }
                        vm.isSubmit = false;
                    }).catch(function (response) {
                        toastr.error(response.data);
                        vm.isSubmit = false;
                    });
                };

                vm.searchCustomers = function () {
                    if (vm.customer.fullName.length > 1) {
                        vm.isSearchingCustomers = true;
                        shoppingCartService.quickSearchCustomers(vm.customer.fullName).then(function (result) {
                            vm.searchedCustomers = result.data;
                        });
                    }
                    else {
                        //vm.customer = { id: 20, fullName: 'Guest' };
                    }
                };

                vm.selectCustomer = function (customer) {
                    vm.customer = customer;
                    vm.isSearchingCustomers = false;
                    $q.all([
                        shoppingCartService.getCart(customer.id),
                        //orderService.getCustomerAddresses(customer.id)
                    ]).then(function (result) {
                        vm.cart = result[0].data;

                        //vm.customerAddress = result[1].data;
                        //if (vm.customerAddress.defaultShippingAddressId) {
                        //    vm.selectedShippingAddressId = vm.customerAddress.defaultShippingAddressId.toString();
                        //}

                        //vm.updateTaxAndShippingPrice();
                    });
                };

                vm.clearFullname = function () {
                    vm.customer.fullName = '';
                    //vm.customer = { id: 20, fullName: 'Guest' };
                }

                vm.resetCart = function () {
                    vm.cart = {};
                    vm.customer = { id: 20, fullName: 'Guest' };
                    vm.cartTable.pagination.totalItemCount = 0;
                }

                //shoppingCartService.getCart(vm.customer.id);
                //getShoppingCartItems();
                vm.getCart();
                vm.getProducts();
            }
        ]);
})();
