<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="http://code.ionicframework.com/1.0.1/css/ionic.css" rel="stylesheet">
    <link href="style.css" rel="stylesheet">
    <script src="http://code.ionicframework.com/1.0.1/js/ionic.bundle.js"></script>
    <script src="js/app.js"></script>
  </head>
<body ng-app="app">

<ion-view view-title="#CircuitoVilaReal Fotos!">
<ion-content ng-controller="CivrInstagramController">
<ion-refresher  refreshing-text="Refreshing.." on-refresh="doRefresh()"></ion-refresher>
<div class="list card" ng-repeat="item in items track by item.id">
  <div class="item item-avatar">
    <img ng-src="{{item.user.profile_picture}}" ng-if="item.user.profile_picture.startsWith('https')">
    <h2>{{item.user.username}}</h2>
  </div>

  <div class="item item-body" >
    <img ng-src="{{item.images.low_resolution.url}}" ng-if="item.images.low_resolution.url.startsWith('https')">
    <p>
      {{item.caption.text}}
    </p>
  </div>

</div>
<ion-infinite-scroll immediate-check="false" on-infinite="loadMore()" distance="5%" ng-if="!noMoreItemsAvailable"></ion-infinite-scroll>
</ion-content>
</ion-view>
  </body>
</html>
/* Styles go here */

(function() {

  var app = angular.module('app', ['ionic']);

  app.factory('PhotoService', function($http, $q) {
    
    var BASE_URL = "https://api.instagram.com/v1/users/30711977/media/recent?access_token=&callback=JSON_CALLBACK";
    var items = [];
    var nextUrl = 0;  // next max tag id - for fetching older photos
    var NewInsta = 0; // min tag id - for fetching newer photos

    return {
      GetFeed: function() {
        return $http.jsonp(BASE_URL).then(function(response) {

          items = response.data.data;
          nextUrl = response.data.pagination.next_max_tag_id;
          NewInsta = response.data.pagination.min_tag_id;
          console.log(nextUrl, NewInsta);

          return items;

        });
      },
      GetNewPhotos: function() {
        return $http.jsonp(BASE_URL + '&min_tag_id=' + NewInsta).then(function(response) {

          items = response.data.data;
          if(response.data.data.length > 0){
            NewInsta = response.data.pagination.min_tag_id;
          }

          return items;

        });
      },
      
      /**
       * Always returns a promise object. If there is a nextUrl, 
       * the promise object will resolve with new instragram results, 
       * otherwise it will always be resolved with [].
       **/
      GetOldPhotos: function() {
        if (typeof nextUrl != "undefined") {
          return $http.jsonp(BASE_URL + '&max_tag_id=' + nextUrl).then(function(response) {
  
            if(response.data.data.length > 0){
              nextUrl = response.data.pagination.next_max_tag_id;
            }
            
            items = response.data.data;
  
  
            return items;
  
          });
        } else {
          var deferred = $q.defer();
          deferred.resolve([]);
          return deferred.promise;
        }
      }
      
    }
  });

   app.controller('CivrInstagramController', function($scope, $timeout, PhotoService) {
    $scope.items = [];
    $scope.newItems = [];
    $scope.noMoreItemsAvailable = false;

    PhotoService.GetFeed().then(function(items) {

      $scope.items = items.concat($scope.items);

    });

    $scope.doRefresh = function() {
      if ($scope.newItems.length > 0) {
        $scope.items = $scope.newItems.concat($scope.items);

        //Stop the ion-refresher from spinning
        $scope.$broadcast('scroll.refreshComplete');

        $scope.newItems = [];
      } else {
        PhotoService.GetNewPhotos().then(function(items) {


          $scope.items = items.concat($scope.items);

          //Stop the ion-refresher from spinning
          $scope.$broadcast('scroll.refreshComplete');
        });
      }
    };
    $scope.loadMore = function() {
      PhotoService.GetOldPhotos().then(function(items) {

        $scope.items = $scope.items.concat(items);

        $scope.$broadcast('scroll.infiniteScrollComplete');
        
        // an empty array indicates that there are no more items
        if (items.length === 0) {
          $scope.noMoreItemsAvailable = true;
        }

      });
    };

  });


  app.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
      if (window.cordova && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      }
      if (window.StatusBar) {
        StatusBar.styleDefault();
      }
    });
  });
}());