(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 = {
                    book: idBook,
                    research_id: $scope.results.hits[index].metas_dict.inventorynumber
                };
                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');
        };
    });
})();
