'use strict';

var VoucherCtrl = ['$scope', '$modal', 'voucher', 'product_groups', function ($scope, $modal, voucher, product_groups) {
        $scope.selectedProduct = -1;
        $scope.voucher = voucher;
        $scope.product_groups = product_groups;
        $scope.products = [];
        $scope.selectProductGroup = function (index) {
            $scope.products = $scope.product_groups[index].Products;
        }
        $scope.printKot = function () {
            return $scope.voucher.$save({type: 'Kot'}, function (u, putResponseHeaders) {
                $scope.toasts.push({Type: 'Success', Message: ''});
                $location.path('/Tables');
            }, function (data, status) {
                $scope.$emit('notification',{Type: 'Danger', Message: data.data});
            });
        }
        $scope.selectProduct = function (isNewKot, index) {
            if (!isNewKot) {
                return;
            }
            $scope.selectedProduct = index;
        }
        $scope.minimumQuantity = voucher.Kots.reduce(function (accumulator, value) {
            return accumulator.concat(value.Inventories);
        }, []).reduce(function (accumulator, value) {
                if (!_.has(accumulator, value.Product.ProductID)) {
                    accumulator[value.Product.ProductID] = -1 * value.Quantity;
                } else {
                    accumulator[value.Product.ProductID] -= value.Quantity;
                }
            }, {});
        $scope.kot = $scope.voucher.Kots[$scope.voucher.Kots.length - 1];
        $scope.addProduct = function (product) {
            var inv,
                index = -1;

            if (!$scope.voucher.PerSeat) {
                for (var i = 0, l = $scope.kot.Inventories.length; i < l; ++i) {
                    if ($scope.kot.Inventories[i].Product.ProductID === product.ProductID) {
                        index = i;
                        inv = $scope.kot.Inventories[i];
                        break;
                    }
                }
                if (index === -1) {
                    $scope.kot.Inventories.push({Product: product, Quantity: 1});
                    index = $scope.kot.Inventories.length - 1;
                } else {
                    inv.Quantity += 1;
                }
                $scope.selectProduct(true, index);
            } else {
                var modalInstance = $modal.open({
                    backdrop: true,
                    templateUrl: '/template/modal/num-pad.html',
                    controller: NumPadController,
                    resolve: {
                        info: function () {
                            return {
                                title: 'Chair No.',
                                init: '0',
                                allowDecimal: false,
                                allowNegative: false
                            }
                        }
                    }
                });
                modalInstance.result.then(function (chair) {
                    for (var i = 0, l = $scope.kot.Inventories.length; i < l; ++i) {
                        if ($scope.kot.Inventories[i].Product.ProductID === product.ProductID && $scope.kot.Inventories[i].Chair == chair) {
                            index = i;
                            inv = $scope.kot.Inventories[i];
                            break;
                        }
                    }
                    if (index === -1) {
                        $scope.kot.Inventories.push({Product: product, Quantity: 1, Chair: chair});
                        index = $scope.kot.Inventories.length - 1;
                    } else {
                        inv.Quantity += 1;
                    }
                    $scope.selectProduct(true, index);
                });
            }
        };

        $scope.delete = function (inventory, index) {
            var minimum = 0,
                qty;
            if (_.has($scope.minimumQuantity, inventory.Product.ProductID)) {
                minimum = $scope.minimumQuantity[inventory.Product.ProductID];
            }
            if (minimum === 0 && inventory.Quantity === 1) {
                var kot = $scope.voucher.Kots[$scope.voucher.Kots.length - 1];
                kot.Inventories.splice(index, 1);
                $scope.selectedProduct = -1;
            }
            if (inventory.Quantity - 1 >= minimum) {
                qty = inventory.Quantity - 1;
            } else {
                qty = minimum;
            }
            if (qty % 1 !== 0) {
                qty = Math.round(qty, -2);
            }
            inventory.Quantity = qty;
        }
        $scope.quantity = function (inventory, index) {
            var modalInstance = $modal.open({
                backdrop: true,
                templateUrl: '/template/modal/num-pad.html',
                controller: NumPadController,
                resolve: {
                    info: function () {
                        return {
                            title: 'Quantity',
                            init: inventory.Quantity.toString(),
                            allowNegative: true,
                            allowDecimal: true
                        }
                    }
                }
            });
            modalInstance.result.then(function (amount) {
                var minimum = 0;
                if (_.has($scope.minimumQuantity, inventory.Product.ProductID)) {
                    minimum = $scope.minimumQuantity[inventory.Product.ProductID];
                }
                if (minimum === 0 && amount <= 0) {
                    var kot = $scope.voucher.Kots[$scope.voucher.Kots.length - 1];
                    kot.Inventories.splice(index, 1);
                    $scope.selectedProduct = -1;
                }
                if (amount >= minimum) {
                    inventory.Quantity = amount;
                } else {
                    inventory.Quantity = minimum;
                }
            });
        };

        $scope.pax = function () {
            var modalInstance = $modal.open({
                backdrop: true,
                templateUrl: '/template/modal/num-pad.html',
                controller: NumPadController,
                resolve: {
                    info: function () {
                        return {
                            title: 'Pax',
                            init: angular.isNumber($scope.voucher.Pax) ? $scope.voucher.Pax.toString() : '0'
                        }
                    }
                }
            });
            modalInstance.result.then(function (amount) {
                $scope.voucher.Pax = amount;
            });
        };

        $scope.perSeat = function () {
            $scope.voucher.perSeat = true;
//            var modalInstance = $modal.open({
//                backdrop: true,
//                templateUrl: '/template/modal/confirm.html',
//                controller: ['$scope', '$modalInstance', function ($scope, $modalInstance) {
//                    $scope.title = "Maintain per seat order details";
//                    $scope.yes = "Per seat";
//                    $scope.no = "Combined";
//                    $scope.ok = function () {
//                        $modalInstance.close();
//                    };
//                    $scope.cancel = function () {
//                        $modalInstance.dismiss('cancel');
//                    };
//                }]
//            });
//            modalInstance.result.then(function () {
//                $scope.voucher.PerSeat = true;
//            }, function () {
//                $scope.voucher.PerSeat = false;
//            });
        };

        if (!$scope.voucher.VoucherID) {
            $scope.pax();
            $scope.perSeat();
        }
    }]
    ;

VoucherCtrl.resolve = {
    voucher: ['$route', 'Voucher', function ($route, Voucher) {
        var id = $route.current.params.id;
        if (typeof id !== 'undefined') {
            return Voucher.get({id: id}).$promise;
        }

        var table = $route.current.params.t;
        return Voucher.get({t: table}).$promise;
    }],
    product_groups: ['ProductGroup', function (ProductGroup) {
        return ProductGroup.tree({}).$promise;
    }]
};

var NumPadController = ['$scope', '$modalInstance', 'info', function ($scope, $modalInstance, info) {
    $scope.title = info.title;
    $scope.allowDecimal = info.allowDecimal || false;
    $scope.allowNegative = info.allowNegative || false;
    $scope.amount = info.init;
    $scope.first = true;
    $scope.addDigit = function (digit) {
        if ($scope.first) {
            $scope.amount = digit;
            $scope.first = false;
            return;
        }
        if ($scope.amount === '0' || $scope.amount === '') {
            $scope.amount = digit;
        } else {
            $scope.amount += digit;
        }
    };
    $scope.delDigit = function () {
        if ($scope.first) {
            $scope.amount = '0';
            $scope.first = false;
            return;
        }
        if ($scope.amount.length === 0) {
            return;
        }
        if ($scope.amount === '0') {
            return;
        }
        $scope.amount = $scope.amount.substr(0, $scope.amount.length - 1);
    }
    $scope.addDecimal = function () {
        if (!$scope.allowDecimal) {
            return;
        }
        if ($scope.first) {
            $scope.amount = '0.';
            $scope.first = false;
            return;
        }
        if ($scope.amount.indexOf('.') !== -1) {
            return;
        }
        if ($scope.amount.length === 0) {
            $scope.amount = '0';
        }
        $scope.amount += '.';
    };
    $scope.negative = function () {
        if (!$scope.allowNegative) {
            return;
        }
        if ($scope.first) {
            $scope.first = false;
        }
        if ($scope.amount.indexOf('-') === 0) {
            $scope.amount = $scope.amount.substr(1);
        } else {
            $scope.amount = '-' + $scope.amount;
        }
    };
    $scope.ok = function () {
        var amount = 0;
        if ($scope.amount === '' || $scope.amount === '0') {
            amount = 0;
        } else if (!$scope.allowDecimal || $scope.amount.indexOf('.') === -1) {
            amount = parseInt($scope.amount);
        } else {
            amount = parseFloat($scope.amount);
        }
        $modalInstance.close(amount);
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
}]