/**
 * Created by sditlev on 22/03/16.
 */


angular.module('mean.themeOne').controller('ArticlesController', ['$scope', '$stateParams', '$location','$timeout', 'Global', 'Articles', 'MeanUser', 'Circles', 'imgurUpload',
    function($scope, $stateParams, $location, $timeout, Global, Articles, MeanUser, Circles, imgurUpload) {

        $scope.global = Global;
        $scope.article = {};

        $scope.article.images = {standard_resolution: {url: 'placeholder'} };

        //Imgur Upload function
        $scope.uploadProgress = 0;
        $scope.uploadFinished = false;
        $scope.sending = false;

        $scope.commentName = null;
        $scope.commentContent = null;
        $scope.commentAuthor = 'Bybonde';

        var imageVariable;

        $scope.$watch('files.length',function(newVal,oldVal){
            $scope.upload($scope.files);
        });

        $scope.upload = function(element) {
            if(element[0]) {
                console.log('image upload initiated: element --> ' + JSON.stringify(element[0]));
                var success = function (result) {
                    console.log('upload succes' + result);
                    $scope.sending = false;
                    $scope.result = result;
                    $scope.uploadFinished = true;
                    $scope.article.images = {standard_resolution: {url: result.data.link}};
                };
                var error = function (err) {
                    console.log('upload-error');
                    $scope.sending = false;
                    $scope.error = err;
                };
                var notify = function (progress) {
                    $timeout(function () {
                        $scope.progress = progress;
                        console.log('upload progress ' + progress)
                    });
                };
                $scope.sending = true;
                $scope.error = false;
                var image = element[0].lfFile;
                var clientId = "8bbdb1b38cd25bf";
                imgurUpload.setClientId(clientId);
                imgurUpload
                    .upload(image)
                    //.upload(image, {clientId: clientId})
                    .then(success, error, notify);
            }
        };


        $scope.hasAuthorization = function(article) {
            if (!article || !article.user) return false;
            return MeanUser.isAdmin || article.user._id === MeanUser.user._id;
        };

        $scope.availableCircles = [];

        Circles.mine(function(acl) {
            $scope.availableCircles = acl.allowed;
            $scope.allDescendants = acl.descendants;
        });

        $scope.showDescendants = function(permission) {
            var temp = $('.ui-select-container .btn-primary').text().split(' ');
            temp.shift(); //remove close icon
            var selected = temp.join(' ');
            $scope.descendants = $scope.allDescendants[selected];
        };

        $scope.selectPermission = function() {
            $scope.descendants = [];
        };

        $scope.create = function(isValid) {
            if (isValid) {
                var article = new Articles($scope.article);
                console.log('************************** Creating article! in controller' + JSON.stringify(article));
                //$scope.article.permissions.push('test test');
                article.$save(function(response) {
                    $location.path('themeOne/' + response._id);
                });

                $scope.article = {};

            } else {
                $scope.submitted = true;
            }
        };

        $scope.remove = function(article) {
            if (article) {
                article.$remove(function(response) {
                    for (var i in $scope.articles) {
                        if ($scope.articles[i] === article) {
                            $scope.articles.splice(i, 1);
                        }
                    }
                    $location.path('themeOne');
                });
            } else {
                $scope.article.$remove(function(response) {
                    $location.path('themeOne');
                });
            }
        };

        $scope.update = function(isValid) {
            if (isValid) {
                var article = $scope.article;
                if (!article.updated) {
                    article.updated = [];
                }
                article.updated.push(new Date().getTime());

                article.$update(function() {
                    $location.path('articles/' + article._id);
                });
            } else {
                $scope.submitted = true;
            }
        };

        $scope.uploadDone = function(){
            return $scope.article.images.standard_resolution.url != 'placeholder'
        };

        $scope.find = function() {
            console.log('articles controller .find() called --> upload done? ' +  $scope.uploadDone());
            Articles.query(function(articles) {
                $scope.articles = articles;
                console.log('articles controller .find() returning --> ' + articles);
                console.log('has auth -->  ' + $scope.availableCircles);
            });
        };

        $scope.findOne = function() {
            Articles.get({
                articleId: $stateParams.articleId
            }, function(article) {
                $scope.article = article;
            });
        };

        $scope.setNewComment = function() {
            if($scope.commentName == null ) $scope.commentName = 'Bybonde';

            var newComment = {name : $scope.commentName, content : $scope.commentContent, author : $scope.commentAuthor ,  created_time : new Date().getTime()};
            if($scope.commentName != null && $scope.commentContent != null){
                var article = $scope.article;
                console.log('New comment --> JSON : ' + JSON.stringify(newComment));
                if (!article.comments) {
                    article.comments = [];
                }
                article.comments.push(newComment);
                console.log('Calling article.$update -->  ');
                article.$update(function() {
                    //$location.path('themeOne/' + article._id);
                    $scope.commentName = null;
                    $scope.commentContent = null;
                    //$scope.commentAuthor = 'Bybonde';
                });
            }
        };
    }
]);