<commit_before>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */

define([
    'angular',
    'lodash',
    'liveblog-edit/unread.posts.service',
    'ng-sir-trevor',
    'ng-sir-trevor-blocks',
    'angular-embed'
], function(angular, _) {
    'use strict';
    var BlogEditController = function (api, $q, $scope, blog, notify, gettext, session, $injector,
        upload, config, embedService, postsService, unreadPostsService, freetypeService, modal,
        blogService, $route, $routeParams, blogSecurityService, themesService, $templateCache, $timeout) {

        var vm = this;
        // @TODO: remove this when theme at blog level.
        // check the theme setting for comments.

        // init with empty vector
        $scope.freetypesData = {}; $scope.freetypeControl = {};

        if (blog.blog_preferences.theme) {
            themesService.get(blog.blog_preferences.theme).then(function(themes) {
                blog.blog_preferences.theme = themes[0];
            });
        }
        // start listening for unread posts.
        unreadPostsService.startListening();
        // return the list of items from the editor
        function getItemsFromEditor() {
            if (!isPostFreetype()) {
                //go with the 'classic' editor items
                return _.map(vm.editor.get(), function(block) {
                    return {
                        group_type: 'default',
                        text: block.text.replace(/(^<div>)|(<\/div>$)/g, '').replace(/(<br>$)/g, ''),
                        meta: block.meta,
                        item_type: block.type
                    };
                });
            } else {
                //this is a freetype post
                return [
                    {
                        group_type: 'freetype',
                        item_type: $scope.selectedPostType.name,
                        text: freetypeService.htmlContent($scope.selectedPostType.template, $scope.freetypesData),
                        meta: {data: $scope.freetypesData}
                    }
                ]
            }
        }

        // determine is current post is classic or freetype
        function isPostFreetype() {
            return $scope.selectedPostType !== 'Default';
        };

        //determine if post is 'scorecard'
        function isPostScorecard() {
            return isPostFreetype() && $scope.selectedPostType.name === 'Scorecard';
        }


        //save the 'keep scoarers' if needed
        function saveScorers() {
                var bp = angular.copy($scope.currentBlog.blog_preferences);
                bp.last_scorecard = $scope.freetypesData;
                return blogService.update($scope.currentBlog, {'blog_preferences': bp});
        }

        // determine if the loaded item is freetype
        function isItemFreetype(itemType) {
            var regularItemTypes = ['text', 'image', 'embed', 'quote', 'comment'];
            if (regularItemTypes.indexOf(itemType) !== -1) {
                return false;
            } else {
                return true;
            }
        }

        function setDefautPostType() {
            return $scope.selectedPostType = 'Default'
        };

        // determine if current editor is not dirty
        function isEditorClean() {
            if (isPostFreetype()) {
                return $scope.freetypeControl.isClean();
            } else {
                var are_all_blocks_empty = _.all(vm.editor.blocks, function(block) {return block.isEmpty();});
                return are_all_blocks_empty || !$scope.isCurrentPostUnsaved();
            }
        }

        // ask in a modalbox if the user is sure to want to overwrite editor.
        // call the callback if user say yes or if editor is empty
        function doOrAskBeforeIfEditorIsNotEmpty(callback, msg) {
            if (isEditorClean()) {
                callback();
            } else {
                msg = msg || gettext('You have content in the editor. You will lose it if you continue without saving it before.');
                modal.confirm(msg).then(callback);
            }
        }

        // remove and clean every items from the editor
        function cleanEditor(actionDisabled) {
            actionDisabled = (typeof actionDisabled === 'boolean') ? actionDisabled : true;
            if ($scope.freetypeControl.reset) {
                $scope.freetypeControl.reset();
            }
            vm.editor.reinitialize();
            $scope.actionDisabled = actionDisabled;
            $scope.currentPost = undefined;
            $scope.sticky = false;
            $scope.highlight = false;
        }

        // retieve the blog's public url
        blogService.getPublicUrl(blog).then(function(url) {
            $scope.publicUrl = url;
        });

        $scope.freetypes = [];
        $scope.selectedFreetype = undefined;
        // retrieve the freetypes
        function getFreetypes() {
            api.freetypes.query().then(function(data) {
                var freetypes = [{
                    name: 'Advertisment Local',
                    template: $templateCache.get('scripts/liveblog-edit/views/ads-local.html')
                }, {
                    name: 'Advertisment Remote',
                    template: $templateCache.get('scripts/liveblog-edit/views/ads-remote.html')
                }, {
                    name: 'Scorecard',
                    template: $templateCache.get('scripts/liveblog-edit/views/scorecards.html'),
                    separator: true
                }];
                $scope.freetypes = freetypes.concat(data._items);
            });
        };

        //load freetype item
        function loadFreetypeItem(item) {
            //find freetype model
            angular.forEach($scope.freetypes, function(freetype, key) {
                if (freetype.name === item.item_type) {
                    $scope.selectedPostType = freetype;
                    $scope.freetypesData = angular.copy(item.meta.data);
                }
            })
        };

        getFreetypes();

        // define the $scope
        angular.extend($scope, {
            blog: blog,
            currentBlog: {},
            panels: {},
            syndicationEnabled: $injector.has('lbNotificationsCountDirective'),
            selectedUsersFilter: [],
            currentPost: undefined,
            blogSecurityService: blogSecurityService,
            unreadPostsService: unreadPostsService,
            preview: false,
            actionPending: false,
            actionDisabled: true,
            sticky: false,
            highlight: false,
            filter: {isHighlight: false},
            selectPostTypeDialog: false,
            selectedPostType: 'Default',
            toggleTypePostDialog: function() {
                $scope.selectPostTypeDialog = !$scope.selectPostTypeDialog;
            },
            selectPostType: function(postType) {
                $scope.selectedPostType = postType;
                $scope.toggleTypePostDialog();
                if (isPostScorecard()) {
                    blogService.get($scope.blog._id).then(function(currentBlog) {
                        $scope.currentBlog = currentBlog;
                        
                        if ($scope.currentBlog.blog_preferences.last_scorecard) {
                            //load latest scorecard
                            if ($scope.currentBlog.blog_preferences.last_scorecard.remember) {
                                $scope.freetypesData = angular.copy($scope.currentBlog.blog_preferences.last_scorecard);
                            }
                        }                     
                    });
                }
            },
            actionStatus: function() {
                if (isPostFreetype()) {
                    if (angular.isDefined($scope.currentPost)) {
                        return $scope.freetypeControl.isClean() && $scope.currentPost.post_status !== 'draft' && $scope.currentPost.post_status !== 'submitted';<commit_msg>fix tests<commit_after>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */

define([
    'angular',
    'lodash',
    'liveblog-edit/unread.posts.service',
    'ng-sir-trevor',
    'ng-sir-trevor-blocks',
    'angular-embed'
], function(angular, _) {
    'use strict';
    var BlogEditController = function (api, $q, $scope, blog, notify, gettext, session, $injector,
        upload, config, embedService, postsService, unreadPostsService, freetypeService, modal,
        blogService, $route, $routeParams, blogSecurityService, themesService, $templateCache, $timeout) {

        var vm = this;
        // @TODO: remove this when theme at blog level.
        // check the theme setting for comments.

        // init with empty vector
        $scope.freetypesData = {}; $scope.freetypeControl = {};

        if (blog.blog_preferences.theme) {
            themesService.get(blog.blog_preferences.theme).then(function(themes) {
                blog.blog_preferences.theme = themes[0];
            });
        }
        // start listening for unread posts.
        unreadPostsService.startListening();
        // return the list of items from the editor
        function getItemsFromEditor() {
            if (!isPostFreetype()) {
                //go with the 'classic' editor items
                return _.map(vm.editor.get(), function(block) {
                    return {
                        group_type: 'default',
                        text: block.text.replace(/(^<div>)|(<\/div>$)/g, '').replace(/(<br>$)/g, ''),
                        meta: block.meta,
                        item_type: block.type
                    };
                });
            } else {
                //this is a freetype post
                return [
                    {
                        group_type: 'freetype',
                        item_type: $scope.selectedPostType.name,
                        text: freetypeService.htmlContent($scope.selectedPostType.template, $scope.freetypesData),
                        meta: {data: $scope.freetypesData}
                    }
                ]
            }
        }

        // determine is current post is classic or freetype
        function isPostFreetype() {
            return $scope.selectedPostType !== 'Default';
        };

        //determine if post is 'scorecard'
        function isPostScorecard() {
            return isPostFreetype() && $scope.selectedPostType.name === 'Scorecard';
        }

        //save the 'keep scoarers' if needed
        function saveScorers() {
                if ($scope.currentBlog.blog_preferences) {
                    var bp = angular.copy($scope.currentBlog.blog_preferences);
                    bp.last_scorecard = $scope.freetypesData;
                    return blogService.update($scope.currentBlog, {'blog_preferences': bp});
                } else {
                    return blogService.get($scope.blog._id).then(function(currentBlog) {
                        $scope.currentBlog = currentBlog;
                        var bp = angular.copy($scope.currentBlog.blog_preferences);
                        bp.last_scorecard = $scope.freetypesData;
                        return blogService.update($scope.currentBlog, {'blog_preferences': bp});
                    })
                }
        }

        // determine if the loaded item is freetype
        function isItemFreetype(itemType) {
            var regularItemTypes = ['text', 'image', 'embed', 'quote', 'comment'];
            if (regularItemTypes.indexOf(itemType) !== -1) {
                return false;
            } else {
                return true;
            }
        }

        function setDefautPostType() {
            return $scope.selectedPostType = 'Default'
        };

        // determine if current editor is not dirty
        function isEditorClean() {
            if (isPostFreetype()) {
                return $scope.freetypeControl.isClean();
            } else {
                var are_all_blocks_empty = _.all(vm.editor.blocks, function(block) {return block.isEmpty();});
                return are_all_blocks_empty || !$scope.isCurrentPostUnsaved();
            }
        }

        // ask in a modalbox if the user is sure to want to overwrite editor.
        // call the callback if user say yes or if editor is empty
        function doOrAskBeforeIfEditorIsNotEmpty(callback, msg) {
            if (isEditorClean()) {
                callback();
            } else {
                msg = msg || gettext('You have content in the editor. You will lose it if you continue without saving it before.');
                modal.confirm(msg).then(callback);
            }
        }

        // remove and clean every items from the editor
        function cleanEditor(actionDisabled) {
            actionDisabled = (typeof actionDisabled === 'boolean') ? actionDisabled : true;
            if ($scope.freetypeControl.reset) {
                $scope.freetypeControl.reset();
            }
            vm.editor.reinitialize();
            $scope.actionDisabled = actionDisabled;
            $scope.currentPost = undefined;
            $scope.sticky = false;
            $scope.highlight = false;
        }

        // retieve the blog's public url
        blogService.getPublicUrl(blog).then(function(url) {
            $scope.publicUrl = url;
        });

        $scope.freetypes = [];
        $scope.selectedFreetype = undefined;
        // retrieve the freetypes
        function getFreetypes() {
            api.freetypes.query().then(function(data) {
                var freetypes = [{
                    name: 'Advertisment Local',
                    template: $templateCache.get('scripts/liveblog-edit/views/ads-local.html')
                }, {
                    name: 'Advertisment Remote',
                    template: $templateCache.get('scripts/liveblog-edit/views/ads-remote.html')
                }, {
                    name: 'Scorecard',
                    template: $templateCache.get('scripts/liveblog-edit/views/scorecards.html'),
                    separator: true
                }];
                $scope.freetypes = freetypes.concat(data._items);
            });
        };

        //load freetype item
        function loadFreetypeItem(item) {
            //find freetype model
            angular.forEach($scope.freetypes, function(freetype, key) {
                if (freetype.name === item.item_type) {
                    $scope.selectedPostType = freetype;
                    $scope.freetypesData = angular.copy(item.meta.data);
                }
            })
        };

        getFreetypes();

        // define the $scope
        angular.extend($scope, {
            blog: blog,
            currentBlog: {},
            panels: {},
            syndicationEnabled: $injector.has('lbNotificationsCountDirective'),
            selectedUsersFilter: [],
            currentPost: undefined,
            blogSecurityService: blogSecurityService,
            unreadPostsService: unreadPostsService,
            preview: false,
            actionPending: false,
            actionDisabled: true,
            sticky: false,
            highlight: false,
            filter: {isHighlight: false},
            selectPostTypeDialog: false,
            selectedPostType: 'Default',
            toggleTypePostDialog: function() {
                $scope.selectPostTypeDialog = !$scope.selectPostTypeDialog;
            },
            selectPostType: function(postType) {
                $scope.selectedPostType = postType;
                $scope.toggleTypePostDialog();
                if (isPostScorecard()) {
                    blogService.get($scope.blog._id).then(function(currentBlog) {
                        $scope.currentBlog = currentBlog;
                        if ($scope.currentBlog.blog_preferences.last_scorecard) {
                            //load latest scorecard
                            if ($scope.currentBlog.blog_preferences.last_scorecard.remember) {
                                $scope.freetypesData = angular.copy($scope.currentBlog.blog_preferences.last_scorecard);
                            }
                        }                     
                    });
                }
            },
            actionStatus: function() {
                if (isPostFreetype()) {
                    if (angular.isDefined($scope.currentPost)) {
                        return $scope.freetypeControl.isClean() && $scope.currentPost.post_status !== 'draft' && $scope.currentPost.post_status !== 'submitted';
{'fraction_non_alphanumeric': 0.10415813790280133, 'fraction_numerical': 0.0011696590443885607, 'mean_word_length': 1.5834718235382987, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6644229', 'n_tokens_mistral': 4468, 'n_tokens_neox': 4195, 'n_words': 920}