(function(){
    'use strict';

    angular.module('ammico', [ 'ngRoute','ammicoHome', 'ammicoMyvisit', 'ammicoBooks', 'ammicoVisites', 'ammicoSlides', 'ammicoSlideshow', 'ammicoSearch', 'ammicoAuth', 'ammicoCommon', 'templates' ])
    .config(function($routeProvider, $httpProvider) {
        $httpProvider.interceptors.push(function($q) {
            return {
                responseError: function(rejection) {
                    if (rejection.status === 401) {
                        localStorage.removeItem('token');
                    }
                    return $q.reject(rejection);
                }
            };
        });
        
        $routeProvider.
        when('/my_visit', {
            controller: 'my_visitCtrl',
            templateUrl: 'my_visit/my_visit.html',
            authRequired: true
        }).
        when('/books', {
            controller: 'booksCtrl',
            templateUrl: 'books/books.html',
            authRequired: true
        }).
        when('/books/:idBook', {
            controller: 'bookCtrl',
            templateUrl: 'books/book.html',
            authRequired: true
        }).
        when('/visites', {
            controller: 'visitesCtrl',
            templateUrl: 'visites/visites.html',
            authRequired: true
        }).
        when('/visites/:idVisit', {
            controller: 'visiteCtrl',
            templateUrl: 'visites/visite.html',
            authRequired: true
        }).
        when('/slide/:idSlide', {
            controller: 'slidesCtrl',
            templateUrl: 'slides/slides.html',
            authRequired: true
        }).
        when('/slideshow/', {
            controller: 'slideshowCtrl',
            templateUrl: 'slideshow/slideshow.html',
            authRequired: true
        }).
        when('/slideshow/:iSlide', {
            controller: 'slideshowCtrl',
            templateUrl: 'slideshow/slideshow.html',
            authRequired: true
        }).
        when('/search/:q', {
            controller: 'searchCtrl',
            templateUrl: 'search/search.html',
            authRequired: true
        }).
        when('/auth/:action', {
            controller: 'authCtrl',
            templateUrl: 'home/home.html',
            authRequired: false
        }).
        otherwise({
            redirectTo: '/my_visit'
        });
    })
    .run( function($rootScope, $location, $window, $http, authApi, context) {
        $rootScope.globals = {};
        if (context.token || localStorage.getItem('token')) {
            $rootScope.globals.userLogged = true;
            localStorage.setItem('token', (context.token || localStorage.getItem('token') ));
            $http.defaults.headers.common.Authorization = 'Token ' + (context.token || localStorage.getItem('token'));
        }
        $rootScope.$on( '$routeChangeStart', function(event, next) {
            if (next.authRequired && !$rootScope.globals.userLogged) {
                $location.path( '/auth/login' );
            }
        });
    });
})();

(function(){
  'use strict';

  angular.module('ammico')
  .controller('routeClassCtrl', function($scope, $location) {
    $scope.isActive = function(route) {
        return route === $location.path();
    };
  });

})();

(function(){
    'use strict';

    angular.module('ammicoAuth',['ngRoute', 'ngMessages'])
    .controller('authCtrl', function($location, $rootScope, $routeParams, $modal){
        $modal.open({
            templateUrl: 'auth/' + $routeParams.action + '_modal.html',
            controller: 'auth' + $routeParams.action + 'Ctrl'
        }).result.then(function (result) {
            $location.path(result);
        }, function () {
            $location.path('/');
        });
    })
    .controller('authloginCtrl', function($modalInstance, $scope, authApi, $window, $http, $rootScope){
        $scope.login = function(){
            authApi.login.save({email:$scope.email, password:$scope.password}, function(data){
                $rootScope.globals.userLogged = true;
                localStorage.setItem('token', data.token);
                $http.defaults.headers.common.Authorization = 'Token ' + localStorage.getItem('token');
                $modalInstance.close('/');
            });
        };
        $scope.register = function () {
            $modalInstance.close('/auth/register');
        };
        $scope.cancel = function () {
            $modalInstance.close('/');
        };
    })
    .controller('authlogoutCtrl', function($modalInstance, $scope, $window, $http, $rootScope){
        localStorage.removeItem('token');
        $rootScope.globals.userLogged = false;
        delete $http.defaults.headers.common.Authorization;
        $scope.cancel = function () {
            $modalInstance.close('/');
        };
    })
    .controller('authregisterCtrl', function($scope, $modalInstance, authApi){
        $scope.message = '';

        $scope.user = {
            email: '',
            password: '',
            confirmPassword: ''
        };

        $scope.submit = function(isValid) {
            console.log(isValid);
            console.log($scope);
            console.log($scope.email);
            if (isValid) {
                authApi.user.save({
                    email: $scope.user.email,
                    password: $scope.user.password,
                }, function(){
                    $modalInstance.close('/auth/login');
                });
            } else {
                $scope.message = 'Il reste toujours des champs invalides';
            }
        };
        $scope.back = function () {
            $modalInstance.close('/auth/login');
        };
    })
    .directive('compareTo', function(){
        return {
            require: 'ngModel',
            scope: {
                otherModelValue: '=compareTo'
            },
            link: function($scope, element, attributes, ngModel) {

                ngModel.$validators.compareTo = function(modelValue) {
                    return modelValue === $scope.otherModelValue;
                };

                $scope.$watch('otherModelValue', function() {
                    ngModel.$validate();
                });
            }
        };
    });
})();

(function(){
    'use strict';

    angular.module('ammicoBooks',['ngRoute', 'ui.sortable'])
    .controller('booksCtrl', function($scope, $location, $modal, Book, Slide){
        $scope.editable = true;
        
        $scope.books = Book.query({type: 'book', format:'json'}, function(data){
            data.sort(function (a, b) {
                return a.date < b.date;
            });

            for (var i = 0; i < data.length; i++) {
                data[i].slides = Slide.query({idBook:data[i].id, limit: 5, format:'json'});
            }
        });
        
//        $scope.$on('slideDeleted', function (event, data) {
//            console.log(data); // 'Data to send'
//        });

        $scope.addBook = function (idParent) {
            $modal.open({
                templateUrl: 'books/add_modal.html',
                controller: 'ModalAddBookCtrl'
            }).result.then(function (title) {
                Book.save({idParent:idParent, title: title}, function(newBook){
                    $scope.books.push(newBook);
                });
            });
        };
    })

    .controller('bookCtrl', function($scope, $location, $routeParams, $modal, Book, Slide, Order) {
        $scope.editable = true;
        
        $scope.book = Book.get({idBook:$routeParams.idBook, format:'json'}, function(data){
            data.slides = Slide.query({idBook: data.id, format:'json'}, function(data){
                data.sort(function (a, b) {
                    return a.orderIndex > b.orderIndex;
                });
            });
        });

        $scope.sortableOptions = {
                stop: function() {
                    var order = $scope.book.slides.map(function(i){
                        return i.id;
                    });
                    Order.save({idBook:$routeParams.idBook}, {order: order});
                }
        };
        
        $scope.deleteItem = function(item){
            if(window.confirm('Êtes-vous sûr(e) de vouloir effacer cet élément ? Cette action est irrémédiable.')){
                Slide.delete({idSlide: item.id}, function(){
                    $scope.book.slides.splice($scope.book.slides.indexOf(item), 1);
                },
                function(error) {
                    if (error.status === 404){
                        $scope.book.slides.splice($scope.book.indexOf(item), 1);
                    }
                });
            }
        };
    })
    .controller('ModalAddBookCtrl', function ($scope, Book, $modalInstance) {

        $scope.add = function(){
            $modalInstance.close($scope.title);
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        }
        ;
        $scope.books = Book.query({format:'json'});
        
        $scope.addToBook = function(idBook){
            $modalInstance.close(idBook);
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    });
})();


(function(){
    'use strict';

    angular.module('ammicoCommon', ['ngRoute'])
    .factory('Book', function($resource, context) {
        var books = $resource(context.urls.ammicoUrl+'books/:idBook', {idBook:'@id', idExpo: context.idExpo}, {update: { method: 'PUT'}});
        return books;
    })
    .factory('Slide', function($resource, context, $modal) {
        var slides = $resource(context.urls.ammicoUrl+'slides/:idSlide', {idSlide:'@id'}, {update: { method: 'PUT'}});

        angular.extend(slides.prototype, {

            toggleFavorite: function () {
                this.favorite = !this.favorite;
                this.$update();
            },
            addToBook: function () {
                var _this = this;
                var modalInstance = $modal.open({
                    templateUrl: 'books/add_book_modal.html',
                    controller: 'ModalAddBookCtrl',
                    size: 'sm'
                });

                modalInstance.result.then(function (idBook) {
                    var newSlide = _this;
                    newSlide.book = idBook;
                    delete newSlide.id;
                    slides.save(newSlide);
                });
            },
            update: function(){
                console.log('test');
            },
            remove: function (array) {
                var _this = this;
                if(window.confirm('Êtes-vous sûr(e) de vouloir effacer cet élément ? Cette action est irrémédiable.')){
                    this.$delete(function(){
                        if (array){
                            array.splice(array.indexOf(_this), 1);
                        }
                        //$scope.$emit('slideDeleted', array);
                    },
                    function(error) {
                        if (error.status === 404 && array){
                                array.splice(array.indexOf(_this), 1);
                        }
                    });
                }
            }
        });

        return slides;
    })
    .factory('Order', function($resource, context) {
        return $resource(context.urls.ammicoUrl+'books/:idBook/order', {idBook:'@id'});
    })
    .service('Utils', function($resource, context, $sce) {
        this.sanitizeUrls = function(data){
            data.details.audio = $sce.trustAsResourceUrl(data.details.audio);
            data.details.video = $sce.trustAsResourceUrl(data.details.video);
            data.audio = $sce.trustAsResourceUrl(data.audio);
            data.video = $sce.trustAsResourceUrl(data.video);
            return data;
        };
    })
    .service('authApi', function($resource, context) {
        this.login = $resource(context.urls.ammicoUrl+'auth/api-token-auth', {idExpo: context.idExpo});
        this.logout = $resource(context.urls.ammicoUrl+'auth/logout');
        this.user = $resource(context.urls.ammicoUrl+'auth/user');
        this.test = $resource(context.urls.ammicoUrl+'auth/auth');
    })
    .service('searchApi', function($resource, context) {
        this.searchResource = function(params){
            return $resource(context.urls.searchUrl,
                    {
                callback: 'JSON_CALLBACK'
                    },
                    {
                        getJsonp: {
                            method: 'JSONP',
                            params: params,
                            isArray: false,
                            transformResponse: function(data){
                              if (data.success){
                                data = data.response[0];
                                for (var i=0; i<data.count; i++){
                                  data.collect[i].name = data.collect[i].name || data.collect[i].title_stop || '';
                                  data.collect[i].description = data.collect[i].description_record || data.collect[i].description_stop || '';
                                  data.collect[i].url = data.collect[i].url_cnhi || '';
                                  data.collect[i].date = data.collect[i].displaydates || '';
                                  data.collect[i].id_stop = data.collect[i].id_stop || '';
                                  data.collect[i].inventorynumber = data.collect[i].inventorynumber || '';
                                  data.collect[i].tags = data.collect[i].tags_stop || [];
                                  data.collect[i].images = data.collect[i].images || [];
                                }
                              }
                              return data;
                            }
                        }
                    });
        };
    })
    .directive('imgType', function(){
        return {
            restrict: 'AE',
            link: function(scope, elem) {
                elem.bind('error', function() {
                    elem.parent().addClass('no-img');
                    elem.remove();
                });
                elem.on('load', function() {
                    var w = elem.width(),
                        h = elem.height();
                    if (w > h){
                        elem.addClass('img-landscape');
                    }
                });
            }
        };
    });

})();

(function(){
    'use strict';


    angular.module('ammicoHome',['ngRoute'])
    .config(function ($routeProvider) {
        $routeProvider
        .when('/', {
            templateUrl: 'home/home.html',
            controller: 'homeCtrl'
        });
    })
    .controller('homeCtrl', function($scope, $location){
        $scope.searchSubmit = function(){
            $location.path('/search/' + $scope.q);
        };
    })
    .filter('meta', function() {
        return function(input, metaName) {
            var nb = input.length, i = 0, found = false;
            while(found===false && i<nb){
                if(input[i].name===metaName){
                    found = true;
                    return input[i].value;
                }
                i++;
            }
            return '';
        };
    });

})();

(function(){
    'use strict';

    angular.module('ammicoMyvisit',['ngRoute', 'ui.sortable'])
    .controller('my_visitCtrl', function($scope, $location, $modal, Book, Slide){

        //get list book
        Book.query({type: 'visit', format:'json'}, function(data){
            data.sort(function (a, b) {
                return a.date > b.date;
            });
            if (data.length >= 1){
                $scope.last_visit = data[0];
                $scope.last_visit.slides = Slide.query({idBook:data[0].id, format:'json'});
            }
        });

        $scope.addBook = function (idParent) {
            $modal.open({
                templateUrl: 'my_visit/add_modal_my_visit.html',
                controller: 'ModalAddMyvisitCtrl'
            }).result.then(function (title) {
                //add book with the title written in the modal
                Book.save({idParent:idParent, title: title}, function(newBook){
                    $scope.books.push(newBook);
                });
            });
        };        
    })
    .controller('ModalAddMyvisitCtrl', function ($scope, $modalInstance) {

        $scope.add = function(){
            $modalInstance.close($scope.title);
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
        $scope.share = function () {
            $modalInstance($scope.book);
        };
    });
})();


(function(){
    'use strict';

    angular.module('ammicoSearch',['ngResource', 'ngRoute', 'ui.bootstrap'])
    .config(function ($routeProvider) {
        $routeProvider
        .when('/', {
            templateUrl: 'search/search.html',
            controller: 'searchCtrl'
        });
    })
    .controller('searchCtrl', function($scope, $location, $routeParams, searchApi, $modal, Slide){
        $scope.q = $routeParams.q || '';
        if ($scope.q !== ''){
          $scope.results = searchApi.searchResource({q:$scope.q, of: 'json', synthesis: 'false', nresults:'10', callback: 'JSON_CALLBACK'}).getJsonp();
        }

        $scope.toggleModal = function (index) {

            var modalInstance = $modal.open({
                templateUrl: 'search/modal.html',
                controller: 'ModalInstanceCtrl',
                size: 'sm'
            });

            modalInstance.result.then(function (idBook) {
              var newSlide = $scope.results.collect[index];
              delete newSlide.date;
              newSlide.book = idBook;
              newSlide.research_id = (newSlide.inventorynumber || newSlide.id_stop);
              Slide.save(newSlide);
            });
        };
    })
    .controller('ModalInstanceCtrl', function ($scope, $modalInstance, Book) {
        $scope.books = Book.query({format:'json'});

        $scope.addToBook = function(idBook){
            $modalInstance.close(idBook);
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    });
})();

(function(){
    'use strict';

    angular.module('ammicoSlides',['ngResource', 'ngRoute'])
    .controller('slidesCtrl', function($scope, $routeParams, Slide, Utils){
        
        $scope.slide = Slide.get({idSlide:$routeParams.idSlide, format:'json'}, function(data){
            data = Utils.sanitizeUrls(data);
        });

    })
    .directive('slideEditor', function() {
        return {
            restrict: 'AE',
            replace: true,
            scope: false,
            templateUrl: 'slides/data_editor.html',
            controller: function($scope){
                $scope.slidesave = function(){
                    if(typeof $scope.slide.tags === 'string'){
                        $scope.slide.tags = $scope.slide.tags.split(',');
                        for (var i = $scope.slide.tags.length - 1; i >= 0; i--) {
                            $scope.slide.tags[i] = $scope.slide.tags[i].trim();
                        }
                    }
                    $scope.slide.editMode = false;
                    $scope.slide.$update({format:'json'});
                };
                $scope.doubleClick = function(){
                    $scope.slide.editMode = true;
                };
            }
        };
    });

})();

(function(){
    'use strict';

    angular.module('ammicoSlideshow',['ngResource', 'ngRoute', 'ui.bootstrap', 'ngTouch'])
    .controller('slideshowCtrl', function($scope, $routeParams, Slide, Book, Utils){
        $scope.slides = Slide.query({idBook:$routeParams.iSlide, format:'json'}, function(data){
            data.forEach(function(slide){
               slide = Utils.sanitizeUrls(slide);
            });
        });
        $scope.book = Book.get({idBook:$routeParams.iSlide, format:'json'});
    });
})();

(function(){
    'use strict';

    angular.module('ammicoVisites',['ngRoute', 'ui.sortable'])
    .controller('visitesCtrl', function($scope, $location, $modal, Book, Slide){

        //get list book
        $scope.visits = Book.query({type: 'visit', format:'json'}, function(data){
            data.sort(function (a, b) {
                return a.date < b.date;
            });

            for (var i = 0; i < data.length; i++) {
                data[i].slides = Slide.query({idBook:data[i].id, limit: 5, format:'json'});
            }    
        });

        $scope.toggleModal = function (index) {

            var modalInstance = $modal.open({
                templateUrl: 'visites/add_book_modal.html',
                controller: 'ModalAddVisitesCtrl',
                size: 'sm'
            });

            modalInstance.result.then(function (idBook) {
                var newSlide = {
                    book: idBook,
                    research_id: $scope.results.hits[index].metas_dict.inventorynumber
                };
                Slide.save(newSlide);
            });
        };


        $scope.addBook = function (idParent) {
            $modal.open({
                templateUrl: 'visites/add_modal_visites.html',
                controller: 'ModalAddVisitesCtrl'
            }).result.then(function (title) {
                //add book with the title written in the modal
                Book.save({idParent:idParent, title: title}, function(newBook){
                    $scope.books.push(newBook);
                });
            });
        };
        
    })


    .controller('visiteCtrl', function($scope, $routeParams, $modal, Book, Slide) {
        //get the slides of a book
      
       $scope.visit = Book.get({idBook:$routeParams.idVisit, format:'json'}, function(data){
           data.slides = Slide.query({idBook: data.id, format:'json'}, function(data){
              data.sort(function (a, b) {
                  return a.orderIndex > b.orderIndex;
              });
          });
       });
       $scope.addBook = function (idParent) {
            $modal.open({
                templateUrl: 'visites/add_modal_visites.html',
                controller: 'ModalAddVisitesCtrl'
            }).result.then(function (title) {
                //add book with the title written in the modal
                Book.save({idParent:idParent, title: title}, function(newBook){
                    $scope.books.push(newBook);
                });
            });
        };
    })


    .controller('ModalAddVisitesCtrl', function($scope, $modalInstance, Book) {

        $scope.add = function(){
            $modalInstance.close($scope.title);
//            ammicoApi.listBooks.save({title: $scope.title}, function(newBook){
//            });
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };

        $scope.books = Book.query({format:'json'});
        
        $scope.addToBook = function(idBook){
            $modalInstance.close(idBook);
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };

    
    });

})();
