angular.module("mediaModal")
    .factory("backgroundPatterns", function($http, $q){
        var _currentPage = 0;
        var _count = 20;

        function search(searchString, page, count){
            return $http.jsonp("http://www.colourlovers.com/api/patterns/top?format=json&jsonCallback=JSON_CALLBACK&numResults=" + _count + "&resultOffset=" + _currentPage)
                .then(function(response){
                    _currentPage++;
                    return {
                        count: 0,
                        images: response.data.map(function(image){
                            return {
                                thumbnail: image.imageUrl,
                                full: image.imageUrl,
                                title: image.title
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        function loadMore(){
            return $http.jsonp("http://www.colourlovers.com/api/patterns/top?format=json&jsonCallback=JSON_CALLBACK&numResults=" + _count + "&resultOffset=" + _currentPage)
                .then(function(response){
                    _currentPage++;
                    return {
                        count: 0,
                        images: response.data.map(function(image){
                            return {
                                thumbnail: image.imageUrl,
                                full: image.imageUrl,
                                title: image.title
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        return {
            search: search,
            loadMore: loadMore
        }
    }
);