angular.module("mediaModal")
    .factory("facebookPhotos", function($http, facebookApiKey, $q){
        var _nextUrl;
        function search(searchString, page, count){
            return $http.get("https://graph.facebook.com/v2.5/" + searchString + "/photos?access_token=" + facebookApiKey)
                .then(function(response){
                    _nextUrl = response.data.paging.next;
                    return {
                        count: 0,
                        images: response.data.data.map(function(user){
                            return {
                                thumbnail: "http://graph.facebook.com/" + user.id + "/picture?type=normal",
                                full: "http://graph.facebook.com/" + user.id + "/picture?type=large",
                                title: user.name
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }

        function loadMore(){

            if (!_nextUrl){
                return $q.reject("no more images");
            }

            return $http.get(_nextUrl)
                .then(function(response){
                    _nextUrl = response.data.paging.next;
                    return {
                        count: 0,
                        images: response.data.data.map(function(user){
                            return {
                                thumbnail: "http://graph.facebook.com/" + user.id + "/picture?type=normal",
                                full: "http://graph.facebook.com/" + user.id + "/picture?type=large",
                                title: user.name
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        return {
            search: search,
            loadMore: loadMore
        }
    }
);