<commit_before>// (C) Copyright 2015 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

angular.module('mm.addons.mod_wiki')

/**
 * Wiki edit page controller.
 *
 * @module mm.addons.mod_wiki
 * @ngdoc controller
 * @name mmaModWikiEditCtrl
 */
.controller('mmaModWikiEditCtrl', function($q, $scope, $stateParams, $mmUtil, $state, $mmaModWiki, $translate, $ionicHistory,
        $mmCourse, $ionicPlatform, $rootScope, mmaModWikiRenewLockTimeout, $interval, $mmText, $mmaModWikiOffline,
        $mmEvents, $mmLang, $mmSite, mmaModWikiComponent, mmaModWikiPageCreatedEvent, $mmaModWikiSync, $mmSyncBlock) {
    var module = $stateParams.module || {},
        courseId = $stateParams.courseid,
        subwikiId = $stateParams.subwikiid || null,
        wikiId = null,
        pageId = $stateParams.pageid || null,
        section = $stateParams.section || null,
        originalBackFunction = $rootScope.$ionicGoBack,
        unregisterHardwareBack,
        originalContent = null,
        editing = false,
        version = false,
        groupId,
        userId,
        rteEnabled,
        subwikiFiles,
        renewLockInterval,
        editOffline = false;

    $scope.saveAndGoParams = false; // See $ionicView.afterLeave.
    $scope.component = mmaModWikiComponent;
    $scope.componentId = module.id;

    $scope.page = {
        title: $stateParams.pagetitle ? $stateParams.pagetitle.replace(/\+/g, " ") : null,
        text: ""
    };

    $scope.canEditTitle = !$stateParams.pagetitle;

    $scope.title = $scope.page.title ? $translate.instant('mma.mod_wiki.editingpage', {'$a': $scope.page.title}) :
        $translate.instant('mma.mod_wiki.newpagehdr');

    if (subwikiId) {
        // Block the subwiki ASAP.
        $mmSyncBlock.blockOperation(mmaModWikiComponent, subwikiId);
    }

    $scope.save = function() {
        var text = $scope.page.text,
            promise,
            modal = $mmUtil.showModalLoading('mm.core.sending', true);

        if (rteEnabled) {
            text = $mmText.restorePluginfileUrls(text, subwikiFiles);
        }

        if (editing) {
            promise = $mmaModWiki.editPage(pageId, text, section).then(function() {
                // Invalidate page since it changed.
                return $mmaModWiki.invalidatePage(pageId).then(function() {
                    return gotoPage();
                });
            });
        } else {
            if (!$scope.page.title) {
                return $mmUtil.showModal('mm.core.notice', 'mma.mod_wiki.titleshouldnotbeempty');
            }

            if (!editOffline) {
                // Check if the user has an offline page with the same title.
                promise = $mmaModWikiOffline.getNewPage(subwikiId, $scope.page.title).then(function() {
                    // There's a page with same name, reject with error message.
                    return $mmLang.translateAndReject('mma.mod_wiki.pageexists');
                }, function() {
                    // Not found, page can be sent.
                });
            } else {
                promise = $q.when();
            }

            promise = promise.then(function() {
                // Try to send the page.
                var instanceId = module && module.instance;
                return $mmaModWiki.newPage(subwikiId, $scope.page.title, text, instanceId).then(function(createdId) {
                    if (createdId) {
                        // Page was created, get its data and go to the page.
                        pageId = createdId;

                        return $mmaModWiki.getPageContents(pageId).then(function(pageContents) {
                            wikiId = pageContents.wikiid;
                            subwikiId = pageContents.subwikiid;
                            // Invalidate subwiki pages since there are new.
                            return $mmaModWiki.invalidateSubwikiPages(pageContents.wikiid).then(function() {
                                return gotoPage();
                            });
                        }).finally(function() {
                            // Notify page created.
                            $mmEvents.trigger(mmaModWikiPageCreatedEvent, {
                                pageid: pageId,
                                subwikiid: subwikiId,
                                pagetitle: $scope.page.title,
                                siteid: $mmSite.getId()
                            });
                        });
                    } else {
                        // Page stored in offline. Go to see the offline page.
                        return gotoNewOfflinePage();
                    }
                });
            });
        }

        return promise.catch(function(message) {
            if (message) {
                $mmUtil.showErrorModal(message);
            } else {
                $mmUtil.showErrorModal('Error saving wiki data.');
            }
        }).finally(function() {
            modal.dismiss();
        });
    };

    // Just ask to confirm the lost of data.
    function cancel() {
        var promise;

        if ((originalContent == $scope.page.text) || (!editing && !$scope.page.text && !$scope.page.title)) {
            promise = $q.when();
        } else {
            // Show confirmation if some data has been modified.
            promise = $mmUtil.showConfirm($translate('mm.core.confirmcanceledit'));
        }

        return promise.then(function() {
            return $ionicHistory.goBack();
        });
    }

    // Check if we need to navigate to a new state.
    function gotoPage() {
        return retrieveModuleInfo(wikiId).then(function() {
            var openPage = false;

            if (!editing && editOffline && backViewPageIsDifferentOffline()) {
                // The user submitted an offline page that isn't loaded in the back view, open it.
                openPage = true;
            } else if (!editOffline && backViewIsDifferentPageOnline()) {
                // The user submitted an offline page that isn't loaded in the back view, open it.
                openPage = true;
            }

            if (openPage) {
                // Setting that will do the app navigate to the page.
                $scope.saveAndGoParams = {
                    module: module,
                    moduleid: module.id,
                    courseid: courseId,
                    pageid: pageId,
                    pagetitle: $scope.page.title,
                    wikiid: wikiId,
                    subwikiid: subwikiId
                };
            }

            return $ionicHistory.goBack();
        }).catch(function() {
            // Go back if fails.
            return $ionicHistory.goBack();
        });
    }

    // Navigate to a new offline page.
    function gotoNewOfflinePage() {
        if (courseId && (module.id || wikiId)) {
            // We have enough data to navigate to the page.
            if (!editOffline || backViewPageIsDifferentOffline()) {
                $scope.saveAndGoParams = {
                    module: module,
                    moduleid: module.id,
                    courseid: courseId,
                    pagetitle: $scope.page.title,
                    wikiid: wikiId,
                    subwikiid: subwikiId
                };
            }
        } else {
            $mmUtil.showModal('mm.core.success','mm.core.datastoredoffline');<commit_msg>MOBILE-1824 wiki: Fix navigation to new offline page<commit_after>// (C) Copyright 2015 <NAME>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

angular.module('mm.addons.mod_wiki')

/**
 * Wiki edit page controller.
 *
 * @module mm.addons.mod_wiki
 * @ngdoc controller
 * @name mmaModWikiEditCtrl
 */
.controller('mmaModWikiEditCtrl', function($q, $scope, $stateParams, $mmUtil, $state, $mmaModWiki, $translate, $ionicHistory,
        $mmCourse, $ionicPlatform, $rootScope, mmaModWikiRenewLockTimeout, $interval, $mmText, $mmaModWikiOffline,
        $mmEvents, $mmLang, $mmSite, mmaModWikiComponent, mmaModWikiPageCreatedEvent, $mmaModWikiSync, $mmSyncBlock) {
    var module = $stateParams.module || {},
        courseId = $stateParams.courseid,
        subwikiId = $stateParams.subwikiid || null,
        wikiId = null,
        pageId = $stateParams.pageid || null,
        section = $stateParams.section || null,
        originalBackFunction = $rootScope.$ionicGoBack,
        unregisterHardwareBack,
        originalContent = null,
        editing = false,
        version = false,
        groupId,
        userId,
        rteEnabled,
        subwikiFiles,
        renewLockInterval,
        editOffline = false;

    $scope.saveAndGoParams = false; // See $ionicView.afterLeave.
    $scope.component = mmaModWikiComponent;
    $scope.componentId = module.id;

    $scope.page = {
        title: $stateParams.pagetitle ? $stateParams.pagetitle.replace(/\+/g, " ") : null,
        text: ""
    };

    $scope.canEditTitle = !$stateParams.pagetitle;

    $scope.title = $scope.page.title ? $translate.instant('mma.mod_wiki.editingpage', {'$a': $scope.page.title}) :
        $translate.instant('mma.mod_wiki.newpagehdr');

    if (subwikiId) {
        // Block the subwiki ASAP.
        $mmSyncBlock.blockOperation(mmaModWikiComponent, subwikiId);
    }

    $scope.save = function() {
        var text = $scope.page.text,
            promise,
            modal = $mmUtil.showModalLoading('mm.core.sending', true);

        if (rteEnabled) {
            text = $mmText.restorePluginfileUrls(text, subwikiFiles);
        }

        if (editing) {
            promise = $mmaModWiki.editPage(pageId, text, section).then(function() {
                // Invalidate page since it changed.
                return $mmaModWiki.invalidatePage(pageId).then(function() {
                    return gotoPage();
                });
            });
        } else {
            if (!$scope.page.title) {
                return $mmUtil.showModal('mm.core.notice', 'mma.mod_wiki.titleshouldnotbeempty');
            }

            if (!editOffline) {
                // Check if the user has an offline page with the same title.
                promise = $mmaModWikiOffline.getNewPage(subwikiId, $scope.page.title).then(function() {
                    // There's a page with same name, reject with error message.
                    return $mmLang.translateAndReject('mma.mod_wiki.pageexists');
                }, function() {
                    // Not found, page can be sent.
                });
            } else {
                promise = $q.when();
            }

            promise = promise.then(function() {
                // Try to send the page.
                var instanceId = module && module.instance;
                return $mmaModWiki.newPage(subwikiId, $scope.page.title, text, instanceId).then(function(createdId) {
                    if (createdId) {
                        // Page was created, get its data and go to the page.
                        pageId = createdId;

                        return $mmaModWiki.getPageContents(pageId).then(function(pageContents) {
                            wikiId = pageContents.wikiid;
                            subwikiId = pageContents.subwikiid;
                            // Invalidate subwiki pages since there are new.
                            return $mmaModWiki.invalidateSubwikiPages(pageContents.wikiid).then(function() {
                                return gotoPage();
                            });
                        }).finally(function() {
                            // Notify page created.
                            $mmEvents.trigger(mmaModWikiPageCreatedEvent, {
                                pageid: pageId,
                                subwikiid: subwikiId,
                                pagetitle: $scope.page.title,
                                siteid: $mmSite.getId()
                            });
                        });
                    } else {
                        // Page stored in offline. Go to see the offline page.
                        return gotoNewOfflinePage();
                    }
                });
            });
        }

        return promise.catch(function(message) {
            if (message) {
                $mmUtil.showErrorModal(message);
            } else {
                $mmUtil.showErrorModal('Error saving wiki data.');
            }
        }).finally(function() {
            modal.dismiss();
        });
    };

    // Just ask to confirm the lost of data.
    function cancel() {
        var promise;

        if ((originalContent == $scope.page.text) || (!editing && !$scope.page.text && !$scope.page.title)) {
            promise = $q.when();
        } else {
            // Show confirmation if some data has been modified.
            promise = $mmUtil.showConfirm($translate('mm.core.confirmcanceledit'));
        }

        return promise.then(function() {
            return $ionicHistory.goBack();
        });
    }

    // Check if we need to navigate to a new state.
    function gotoPage() {
        return retrieveModuleInfo(wikiId).then(function() {
            var openPage = false;

            if (!editing && editOffline && backViewPageIsDifferentOffline()) {
                // The user submitted an offline page that isn't loaded in the back view, open it.
                openPage = true;
            } else if (!editOffline && backViewIsDifferentPageOnline()) {
                // The user submitted an offline page that isn't loaded in the back view, open it.
                openPage = true;
            }

            if (openPage) {
                // Setting that will do the app navigate to the page.
                $scope.saveAndGoParams = {
                    module: module,
                    moduleid: module.id,
                    courseid: courseId,
                    pageid: pageId,
                    pagetitle: $scope.page.title,
                    wikiid: wikiId,
                    subwikiid: subwikiId
                };
            }

            return $ionicHistory.goBack();
        }).catch(function() {
            // Go back if fails.
            return $ionicHistory.goBack();
        });
    }

    // Navigate to a new offline page.
    function gotoNewOfflinePage() {
        if (courseId && (module.id || wikiId)) {
            // We have enough data to navigate to the page.
            if (!editOffline || backViewPageIsDifferentOffline()) {
                $scope.saveAndGoParams = {
                    module: module,
                    moduleid: module.id,
                    courseid: courseId,
                    pageid: null,
                    pagetitle: $scope.page.title,
                    wikiid: wikiId,
                    subwikiid: subwikiId
                };
            }
        } else {
            $mmUtil.showModal('mm.core.success','mm.core.datastoredoffline');
{'fraction_non_alphanumeric': 0.10472909489508299, 'fraction_numerical': 0.001252740369558409, 'mean_word_length': 1.5697730564944472, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '659203', 'n_tokens_mistral': 4294, 'n_tokens_neox': 4080, 'n_words': 1024}