
angular.module("myApp").controller('homeController', function ($scope,$http, $state,News, $window,$stateParams,Catagories,LatestNews) {

        $scope.catagories = Catagories.query();

        $scope.currentPage = 1
        ,$scope.numPerPage = 6
        ,$scope.maxSize = 5;
        $scope.catagoriDetail = Catagories.get({}, {myCatagoriesId: $stateParams.catagoriId}).$promise.then(
                    function (value) {
                        $scope.todos = value.news;
                        $scope.catagori = value;
                        $scope.numPages = function () {
                            return Math.ceil($scope.todos.length / $scope.numPerPage);
                        };
                        console.log( $scope.todos.length);
                        $scope.$watch('currentPage + numPerPage', function () {
                            var begin = (($scope.currentPage - 1) * $scope.numPerPage)
                                , end = begin + $scope.numPerPage;
                            $scope.myNews = $scope.todos.slice(begin, end);

                        });
                    },
                    function (error) {
                        console.log()
                    }
                );

        $scope.newsById = News.get({}, {myNewsId: $stateParams.Id1});

        $scope.show = function(id){
            $scope.newestNews = LatestNews.get({}, {CatagoriesId: id});
        };

        $scope.catagoriById = Catagories.get({}, {myCatagoriesId: $stateParams.myCatagoriId});

        //Delete News
        $scope.deleteNews = function(newsId) {
            if (confirm("Delete?")) {
                $http({
                    method: 'DELETE',
                    url: 'http://localhost:8080/api/HR/news/' + newsId,
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(function (response) {
                    console.log("delete OK");
                    $state.reload();
                }, function (data, status) {
                    $state.reload();
                });
            }
        };

        //Edit news
        $scope.newsEditById = News.get({}, {myNewsId: $stateParams.myNewsEditId});
        $scope.editNews = function(newsEditById) {
            if(confirm("Update?")) {
                $http({
                    method: 'PUT',
                    url: 'http://localhost:8080/api/HR/news/' + newsEditById.id,
                    data: angular.toJson(newsEditById),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(function (response) {
                    console.log("update OK");
                    $state.go('newsManagement',{myCatagoriId:$stateParams.myCatagoriEditId});
                }, function (data, status) {
                    console.log(status);
                });
            }
        };




});