angular.module("mediaModal")
.controller("webServicesController", function($scope, webStorage, enums){
        $scope.currentPage = 0;
        $scope.itemsOnPage = 25;
        $scope.search = function(){
            $scope.appState.loading = true;
            webStorage.search($scope.webServiceType, $scope.imageFilter, $scope.currentPage, $scope.itemsOnPage)
                .then(
                    function(result){
                        $scope.fullImagesCount = result.count;
                        $scope.images = result.images;
                    }
                )
                .finally(
                    function(){
                        $scope.appState.loading = false;
                    }
                );
        };

        $scope.loadMore = function(){
            $scope.appState.loading = true;
            webStorage.loadMore($scope.webServiceType)
                .then(function(result){
                    if (!$scope.images){
                        $scope.images = [];
                    }
                    $scope.images = $scope.images.concat(result.images);
                })
                .finally(function(){
                    $scope.appState.loading = false;
                });
        };

        $scope.setWebServiceType = function(webServiceType){
            $scope.webServiceType = webServiceType;
        };

        $scope.selectImage = function(image){
            image.selected = !image.selected;
            if ($scope.selectedImages){
                if (image.selected){
                    $scope.selectedImages.push(image);
                    return;
                }
                var imageIndex = $scope.selectedImages.indexOf(image);
                if (imageIndex != -1){
                    $scope.selectedImages.splice(imageIndex, 1);
                }
            }
        };

        $scope.showSearcher = function(){
            return $scope.webServiceType !== enums.webServiceTypes.backgroundPatterns;
        };

        $scope.$on("currentResourceChanged", function(event, resourceType){
            if ($scope.webServiceType === enums.webServiceTypes.backgroundPatterns && resourceType === enums.webServiceTypes.backgroundPatterns){
                $scope.search();
            }
        })
    }
);