angular.module("mediaModal")
.factory("instagram", function($http, instagramApiKey, $q){
        var _nextUrl;
        function search(searchString, page, count){
            return $http.jsonp("https://api.instagram.com/v1/tags/" + searchString +"/media/recent?access_token=" + instagramApiKey + "&callback=JSON_CALLBACK&count=20")
                .then(function(response){
                    _nextUrl = response.data.pagination.next_url;
                    return {
                        count: 0,
                        images: response.data.data.map(function(image){
                            return {
                                thumbnail: image.images.thumbnail.url,
                                full: image.images.standard_resolution.url,
                                title: image.caption.text.substr(0, 50)
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }

        function loadMore(){
            if (!_nextUrl){
                return $q.reject("no more images");
            }
            return $http.jsonp(_nextUrl + "&callback=JSON_CALLBACK")
                .then(function(response){
                    _nextUrl = response.data.pagination.next_url;
                    return {
                        count: 0,
                        images: response.data.data.map(function(image){
                            return {
                                thumbnail: image.images.thumbnail.url,
                                full: image.images.standard_resolution.url,
                                title: image.caption.text.substr(0, 50)
                            };
                        })
                    };
                },
                function(response){
                    return $q.reject(response.data);
                }
            );
        }
        return {
            search: search,
            loadMore: loadMore
        }
    }
);