angular.module("mediaModal")
.factory("flickr", function($http, flickrApiKey){
        var _lastPage = 1;
        var _count = 50;
        var _searchString = "";
        function search(searchString, page, count){
            _lastPage = 1;
            _count = count;
            _searchString = searchString;
            return $http.get("https://api.flickr.com/services/rest/?api_key=" + flickrApiKey +
                "&format=json&nojsoncallback=1&method=flickr.photos.search&format=json&page=" + page + "&per_page="
                + count +"&text=" + searchString)
                .then(function(response){

                    return {
                        count: +response.data.photos.total,
                        images: response.data.photos.photo.map(function(photo){
                            return {
                                thumbnail: "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_t.jpg",
                                full: "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + ".jpg"
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        function loadMore(){
            _lastPage++;
            return $http.get("https://api.flickr.com/services/rest/?api_key=" + flickrApiKey +
                "&format=json&nojsoncallback=1&method=flickr.photos.search&format=json&page=" + _lastPage + "&per_page="
                + _count +"&text=" + _searchString)
                .then(function(response){
                    return {
                        count: +response.data.photos.total,
                        images: response.data.photos.photo.map(function(photo){
                            return {
                                thumbnail: "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_t.jpg",
                                full: "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + ".jpg"
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        return {
            search: search,
            loadMore: loadMore
        }
    }
);