<!doctype html>
<html ng-app="myApp" >
<head>
  <meta charset="utf-8">
  <title>AngularJS $http example</title>
  <link rel="stylesheet" href="style.css">
  <script type="text/javascript" src="http://code.angularjs.org/1.0.1/angular-1.0.1.js"></script>
  <script type="text/javascript" src="http://code.angularjs.org/1.0.1/angular-resource-1.0.1.js"></script>
  <script type="text/javascript" src="http://code.angularjs.org/1.0.1/angular-mocks-1.0.1.js"></script>
  <script type="text/javascript" src="controllers.js"></script>
  <script type="text/javascript" src="app.js"></script>
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div ng-controller="FriendCtrl">
        <h2>Mes {{friends.length}} amis</h2>
        <div ng-view></div>
    </div>
</div>
</body>
</html>
<ul>
    <li ng-repeat="friend in friends">
          <h3>{{friend.name}}</h3>
          <a ng-href="#" ng-click="editFriend(friend._id)">Editer</a>
          <a ng-href="#" ng-click="deleteFriend(friend._id)">Supprimer</a>
    </li>
</ul>
<a class="btn btn-primary" ng-href="#/edit" ng-click="addFriend()">Ajouter un ami</a>
<form name="editForm" class="form-horizontal" ng-submit="saveFriend()">
    <label class="control-label"><b>Ami : </b></label>
    <input type="text" name="nom" ng-model="selectedFriend.name" required>
    <div class="form-actions">
        <a class="btn" ng-href="#/list">Retour</a>
        <input class="btn btn-success" ng-click="saveFriend()" value="Enregistrer"/>
    </div>
</form>
// controllers module
angular.module("myApp.controllers", [])
  
  .controller('FriendCtrl', ['$scope', '$http', '$location', function($scope, $http, $location) {
    $scope.url = '/api/friends';
    // query friends method
    $scope.listFriends = function() {
      // call GET http method
      $http.get($scope.url).success(function (data) {
        $scope.friends = data;
      }).error(function(err) {
        console.log("get error : "+err);
      });
    };
    $scope.setSelectedFriend = function(friend) {
      $scope.selectedFriend = friend;
    };
    // first, query all friends to intialize $scope.friends
    $scope.listFriends();
  }])
  
  .controller('FriendListCtrl', ['$scope', '$http', '$location', function($scope, $http, $location) {
    // add friend method
    $scope.addFriend = function() {
      // instanciate a new Friend object
      $scope.setSelectedFriend({});
    };
    // edit friend method
    $scope.editFriend = function(id) {
      // call GET http method of Friend class
      $http.get($scope.url + '/' + id).success(function(data) {
        $scope.setSelectedFriend(data);
        $location.path("/edit");
      }).error(function(err) {
        console.log("get by id error : "+err);
      });
    };
    // delete friend method
    $scope.deleteFriend = function(id) {
      // call DELETE http method
      $http.delete($scope.url + '/' + id).success(function(data) {
        $scope.setSelectedFriend(null);
        $scope.listFriends();
      }).error(function(err) {
        console.log("delete error : "+err);
      });
    };
  }])
  
  .controller('FriendEditCtrl', ['$scope', '$http', '$location', function($scope, $http, $location) {
    // save friend method : use POST if is new one, PUT if it already exists
    $scope.saveFriend = function() {
      if (!$scope.selectedFriend._id) {
        // call POST http method
        $http.post($scope.url, $scope.selectedFriend).success(function(data) {
          $scope.setSelectedFriend(null);
          $scope.listFriends();
        }).error(function(err) {
          console.log("Friend.save() error : "+err);
        });
      } else {
        // call PUT http method
        $http.put($scope.url, $scope.selectedFriend).success(function(data) {
          $scope.setSelectedFriend(null);
          $scope.listFriends();
        }).error(function(err) {
          console.log("put error : "+err);
        });
      }
      // return to /list
      $location.path("/list");
    };
  }]);
// myApp module with myApp.controllers dependency containing all controllers
// and ngMockE2E dependency containing $httpBackend service
angular.module('myApp', ['myApp.controllers', 'ngMockE2E'])
  // routes declaration
  .config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/edit', {
        templateUrl: 'partial_edit.html',
        controller: 'FriendEditCtrl'
    });
    $routeProvider.when('/list', {
        templateUrl: 'partial_list.html',
        controller: 'FriendListCtrl'
    });
    $routeProvider.otherwise({ redirectTo: '/list' });
  }])
  // application initialization : declare $httpBackend.when*() behaviors
  .run(function($httpBackend) {    
    // the database list of friends
    var friendList = [ 
        { _id: 1234567, name: 'Misko Hevery'},
        { _id: 2345678, name: 'Igor Minar'},
        { _id: 3456789, name: 'Vojta Jina'}
    ];
    // simple method to retrieve array index by id (should use underscore.js)
    function friendIndexById(id) {
      if (!id) return null;
      var index = -1;
      
      for(var i = 0; i < friendList.length; i++) {
        var o = friendList[i];
        if (id == o._id) {
          index = i;
          break;
        }
      }
    
      return index;
    }

    // catch GET call and return friends object
    $httpBackend.whenGET(/\/api\/friends(\/\d*)*/)
                .respond(function(method, url, data, headers) {      
      console.log("GET -> " + url);
      var parts = url.replace("/api/friends", "").split("/");
      if (parts.length != 2) {
        return [200, friendList.slice()];        
      }
    
      var id = parts[1];
    
      var index = friendIndexById(id);
    
      if (index != -1) {
        console.log("GET -> " + friendList[index].name);
        return [200, friendList[index]];
      }
    
      return [404, "NOT-FOUND"];
    });

    // catch POST call and add friend object to friend list
    $httpBackend.whenPOST("/api/friends").respond(function(method, url, data, headers) {
      console.log("POST -> " + url);
      var o = angular.fromJson(data);    
      o._id = new Date().getTime(); 
      friendList.push(o);    
      return [200, "Success"];
    });
  
    // catch PUT call and update friend objec already exist in friend list
    $httpBackend.whenPUT(/\/api\/friends(\/\d*)*/).respond(function(method, url, data, headers) {
      console.log("PUT -> " + url);  
      
      var o = angular.fromJson(data);
      var index = friendIndexById(o._id);
  
      if (index != -1) {
        friendList[index] = o;
        return [200, 'SUCCESS!!'];
      }
      
      return [404, 'NOT-FOUND!!'];
    });
      
    // catch DELETE call and remove friend object in friend list
    $httpBackend.whenDELETE(/\/api\/friends\/\d*/).respond(function(method, url, data, headers) {
      console.log("DELETE -> " + url);  
      
      var parts = url.replace("/api/friends", "").split("/");
      if (parts.length != 2) {
          return [409, "invalid id"];        
      }
      
      var id = parts[1];
  
      var index = friendIndexById(id);
  
      if (index != -1) {
        friendList.splice(index, 1);
        return [200, 'SUCCESS!!'];
      }
      
      return [404, 'NOT-FOUND!!'];
    });
    
    // catch routes call and pass through
    $httpBackend.whenGET(/^partial.*/).passThrough();  
});

/* Put your css in here */