App.config(function ($routeProvider) {

    $routeProvider.when(BASE_URL + "/mcommerce/mobile_cart/index/value_id/:value_id", {
        controller: 'MCommerceCartViewController',
        templateUrl: BASE_URL + "/mcommerce/mobile_cart/template",
        code: "mcommerce-cart"
    });

}).controller('MCommerceCartViewController', function ($scope, $routeParams, $location, Pictos, McommerceCart, Message, Url) {

    $scope.$watch("isOnline", function (isOnline) {
        $scope.has_connection = isOnline;
        $scope.loadContent();
    });

    $scope.is_loading = true;

    McommerceCart.value_id = $routeParams.value_id;
    $scope.value_id = $routeParams.value_id;

    $scope.pictos = {
        trash: Pictos.get("trash", "background"),
        shopping_cart: Pictos.get("shopping_cart", "background")
    };
    
    $scope.loadContent = function () {
        McommerceCart.find().success(function (data) {

            $scope.cart = data.cart;

            if ($scope.cart.valid) {
                $scope.header_right_button = {
                    action: $scope.goToOverview,
                    title: "Proceed"
                };
            }

        }).finally(function () {
            $scope.is_loading = false;
        });
    };

    $scope.goToOverview = function () {

        if(!$scope.is_loading) {
            $scope.is_loading = true;
            $location.path(Url.get("mcommerce/mobile_sales_customer/index", {
                value_id: $routeParams.value_id
            }));
        }
    };

    $scope.goToCategories = function () {
        $location.path(Url.get("mcommerce/mobile_category/index", {
            value_id: $routeParams.value_id
        }));
    };

    $scope.removeLine = function (line) {
        McommerceCart.deleteLine(line.id).success(function (data) {
            if (data.success) {
                if (angular.isDefined(data.message)) {
                    $scope.message = new Message();
                    $scope.message.setText(data.message)
                        .isError(false)
                        .show();
                }
                // update content
                $scope.loadContent();
            }
        }).error(function (data) {
            if (data && angular.isDefined(data.message)) {
                $scope.message = new Message();
                $scope.message.isError(true)
                    .setText(data.message)
                    .show();
            }
        });
    };

});