<commit_before>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community 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://opensource.org/licenses/ECL-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.
 */

define(['jquery', 'oae.core', 'moment', 'bootstrap', 'bootstrap.datetimepicker'], function($, oae, moment) {

    var notifications = {
        'schedule': false,
        'vote': false
    };

    /**
     * Change the active view
     *
     * @param  {String} pageToActive    id of the view to active
     * @return {void}                   null
     */
    var toggleActiveView = function (viewToActive) {

        var pages = ['loodle', 'add-schedule', 'delete-schedule'];

        // Show the chosen page
        pages.forEach(function (page) {
            $('#' + page + '-page').addClass('hide');
            $('#' + page).parent().removeClass('active');
        });

        //  Active the correct item on the navbar
        $('#' + viewToActive + '-page').toggleClass('hide');
        $('#' + viewToActive).parent().addClass('active');

        // Keep trace of the active view
        currentView = viewToActive;

    };

    /**
     * Format the loodle's schedules to easily display the loodle
     *
     * @param  {Object} loodle  loodle data
     * @return {void}           null
     */
    var formatSchedules = function (loodle, lang) {

        if (loodle.schedules.length === 0)
            return;

        // Keep trace of the default schedules array
        loodle.defaultSchedules = [];

        // Format the schedules to display them in the current language
        $.each(loodle.schedules, function (key, schedule) {
            schedule.begin_time = moment(schedule.begin_time).locale(lang.split('_')[0]);
            schedule.end_time = moment(schedule.end_time).locale(lang.split('_')[0]);

            loodle.defaultSchedules.push(schedule);
        });

        var months = [];
        var days   = [];
        var hours  = [];

        loodle.schedules.forEach(function (schedule) {

            // Format to the locale lang
            var moment_begin_time = moment(schedule.begin_time).locale(lang.split('_')[0]);
            var moment_end_time   = moment(schedule.end_time).locale(lang.split('_')[0]);

            // MONTHS ==============================================

            // If we have no months registred, we just add the first one we check
            if (months.length === 0) {
                months.push({
                    time: moment_begin_time,
                    nbSchedules: 2
                });
            }
            // Else, we check if the current month we are looking at is already registred,
            // ie if we already have the same month in a previous schedule. If it's the case
            // we do not add the same month again but instead we increment by 2 the number of
            // schedules registred in this month.
            else {
                var monthAlreadyPresent = false;

                months.forEach(function (month) {
                    if (month.time.format('MMMM YYYY') === moment_begin_time.format('MMMM YYYY')) {
                        monthAlreadyPresent = true;
                        month.nbSchedules += 2;
                    }
                });

                // No schedule already registred with that month, we add it
                if (!monthAlreadyPresent) {
                    months.push({
                        time: moment_begin_time,
                        nbSchedules: 2
                    });
                }
            }

            // DAYS ==============================================

            // If we have no days registred, we just add the first one we check
            if (days.length === 0) {
                days.push({
                    time: moment_begin_time,
                    nbSchedules: 2
                });
            }
            // Else, we check if the current day we are looking at is already registred,
            // ie if we already have the same day in a previous schedule. If it's the case
            // we do not add the same day again but instead we increment by 2 the number of
            // schedules registred in this day.
            else {
                var dayAlreadyPresent = false;

                days.forEach(function (day) {
                    if (day.time.format('dddd D') === moment_begin_time.format('dddd D')) {
                        dayAlreadyPresent = true;
                        day.nbSchedules += 2;
                    }
                });

                // No schedule already registred with that day, we add it
                if(!dayAlreadyPresent) {
                    days.push({
                        time: moment_begin_time,
                        nbSchedules: 2
                    });
                }
            }

            // HOURS ==============================================
            hours.push(moment_begin_time);
            hours.push(moment_end_time);

            schedule.begin_time = moment(schedule.begin_time);
            schedule.end_time   = moment(schedule.end_time);

            loodle.schedules.months = months;
            loodle.schedules.days   = days;
            loodle.schedules.hours  = hours;

        });

    };

    /**
     * Format the loodle's users to easily display the loodle
     *
     * @param  {Object} loodle  loodle data
     */
    var formatUsers = function (loodle) {

        if (loodle.users.length === 0)
            return;

        loodle.users.forEach(function (user) {

            user.votes = [];

            loodle.votes.forEach(function (vote) {
                if (user.id === vote.user_id)
                    user.votes.push(vote);
            });
        });

    };

    /**
     * Handle the notifications to send
     *
     * @param  {String}     widgetId    Widget identifier
     * @param  {String}     type        Notification type
     */
    var handleNotifications = function (widgetData, type) {

        var alreadySend = false;
        var notificationType = '';

        // We do not send notifications on update from public users
        if (!widgetData.loodleData.currentUser.status === 'temporary') {

            $.each(notifications, function (key, isAlreadySend) {
                if (key === type) {
                    if (isAlreadySend) {
                        alreadySend = true;
                    } else {
                        notifications[key] = true;
                        notificationType = key;
                    }
                }
            });

            if (!alreadySend) {
                oae.api.doodle.sendNotifications(widgetData.id, notificationType, function (err) {
                    if (err) {
                        console.log('An error occured : ', err);
                        oae.api.util.notification(
                            oae.api.i18n.translate('__MSG__DOODLE_NOTIFICATIONS_NOT_SENT__', 'doodle'),
                            oae.api.i18n.translate('__MSG__DOODLE_NOTIFICATIONS_COULD_NOT_BE_SENT__', 'doodle'));
                    }
                });
            }

        }

    };

    /**
     * Update the view of the loodle with the current loodle data
     *
     * @param  {Object}     widgetData      Widget data
     * @param  {String}     locale          Language currently use by the user
     */
    var updateLoodleDisplay = function (widgetData, locale) {

        oae.api.doodle.getData(widgetData.loodleData.id, function (err, loodle) {

            if (err) {
                console.log('An error occured trying to get the loodle data : ', err);
                oae.api.util.notification(
                    oae.api.i18n.translate('__MSG__UNEXPECTED_ERROR__', 'doodle'),
                    oae.api.i18n.translate('__MSG__DOODLE_DISPLAY_COULD_NOT_BE_UPDATED__', 'doodle'));
                return;
            }

            // Sort the users array so that the current user always has his name at the bottom of the table
            var index = 0;
            var currentUser = {};
            for (var i = 0; i < loodle.users.length; i++) {
                if (loodle.users[i].id == widgetData.loodleData.currentUser.id) {
                    index = i;
                    currentUser = loodle.users[i];
                }
            }


            loodle.users.splice(index, 1);
            loodle.users.push(currentUser);

            // We keep a trace of the current user
            loodle.currentUser = widgetData.loodleData.currentUser;

            // Format loodle data to easily display
            formatSchedules(loodle, oae.data.me.locale);
            formatUsers(loodle);<commit_msg>Resolution of a bug that sometimes showed the votes of the users not in order.<commit_after>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community 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://opensource.org/licenses/ECL-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.
 */

define(['jquery', 'oae.core', 'moment', 'bootstrap', 'bootstrap.datetimepicker'], function($, oae, moment) {

    var notifications = {
        'schedule': false,
        'vote': false
    };

    /**
     * Change the active view
     *
     * @param  {String} pageToActive    id of the view to active
     * @return {void}                   null
     */
    var toggleActiveView = function (viewToActive) {

        var pages = ['loodle', 'add-schedule', 'delete-schedule'];

        // Show the chosen page
        pages.forEach(function (page) {
            $('#' + page + '-page').addClass('hide');
            $('#' + page).parent().removeClass('active');
        });

        //  Active the correct item on the navbar
        $('#' + viewToActive + '-page').toggleClass('hide');
        $('#' + viewToActive).parent().addClass('active');

        // Keep trace of the active view
        currentView = viewToActive;

    };

    /**
     * Format the loodle's schedules to easily display the loodle
     *
     * @param  {Object} loodle  loodle data
     * @return {void}           null
     */
    var formatSchedules = function (loodle, lang) {

        if (loodle.schedules.length === 0)
            return;

        // Keep trace of the default schedules array
        loodle.defaultSchedules = [];

        // Format the schedules to display them in the current language
        $.each(loodle.schedules, function (key, schedule) {
            schedule.begin_time = moment(schedule.begin_time).locale(lang.split('_')[0]);
            schedule.end_time = moment(schedule.end_time).locale(lang.split('_')[0]);

            loodle.defaultSchedules.push(schedule);
        });

        var months = [];
        var days   = [];
        var hours  = [];

        loodle.schedules.forEach(function (schedule) {

            // Format to the locale lang
            var moment_begin_time = moment(schedule.begin_time).locale(lang.split('_')[0]);
            var moment_end_time   = moment(schedule.end_time).locale(lang.split('_')[0]);

            // MONTHS ==============================================

            // If we have no months registred, we just add the first one we check
            if (months.length === 0) {
                months.push({
                    time: moment_begin_time,
                    nbSchedules: 2
                });
            }
            // Else, we check if the current month we are looking at is already registred,
            // ie if we already have the same month in a previous schedule. If it's the case
            // we do not add the same month again but instead we increment by 2 the number of
            // schedules registred in this month.
            else {
                var monthAlreadyPresent = false;

                months.forEach(function (month) {
                    if (month.time.format('MMMM YYYY') === moment_begin_time.format('MMMM YYYY')) {
                        monthAlreadyPresent = true;
                        month.nbSchedules += 2;
                    }
                });

                // No schedule already registred with that month, we add it
                if (!monthAlreadyPresent) {
                    months.push({
                        time: moment_begin_time,
                        nbSchedules: 2
                    });
                }
            }

            // DAYS ==============================================

            // If we have no days registred, we just add the first one we check
            if (days.length === 0) {
                days.push({
                    time: moment_begin_time,
                    nbSchedules: 2
                });
            }
            // Else, we check if the current day we are looking at is already registred,
            // ie if we already have the same day in a previous schedule. If it's the case
            // we do not add the same day again but instead we increment by 2 the number of
            // schedules registred in this day.
            else {
                var dayAlreadyPresent = false;

                days.forEach(function (day) {
                    if (day.time.format('dddd D') === moment_begin_time.format('dddd D')) {
                        dayAlreadyPresent = true;
                        day.nbSchedules += 2;
                    }
                });

                // No schedule already registred with that day, we add it
                if(!dayAlreadyPresent) {
                    days.push({
                        time: moment_begin_time,
                        nbSchedules: 2
                    });
                }
            }

            // HOURS ==============================================
            hours.push(moment_begin_time);
            hours.push(moment_end_time);

            schedule.begin_time = moment(schedule.begin_time);
            schedule.end_time   = moment(schedule.end_time);

            loodle.schedules.months = months;
            loodle.schedules.days   = days;
            loodle.schedules.hours  = hours;
        });

    };

    /**
     * Format the loodle's users to easily display the loodle
     *
     * @param  {Object} loodle  loodle data
     */
    var formatUsers = function (loodle) {

        if (loodle.users.length === 0)
            return;

        loodle.users.forEach(function (user) {

            user.votes = [];

            loodle.votes.forEach(function (vote) {
                if (user.id === vote.user_id) {
                    user.votes.push(vote);
                }
            });

            formatVotes(user, loodle);
        });



    };

    /**
     * Format the user votes in time order
     * @param votes
     */
    var formatVotes = function (user, loodle) {

        var orderedVotes = [];
        for (var i = 0; i < user.votes.length; i++) {
            orderedVotes[i] = null;
        }

        user.votes.forEach(function (vote) {
            // Detect the position of the schedule
            var index = 0;
            for (var i = 0; i < loodle.defaultSchedules.length; i++) {
                if (loodle.defaultSchedules[i].id == vote.schedule_id) {
                    index = i;
                }
            }

            // Put the vote in the right position in the ordered array
            orderedVotes[index] = vote;
        });

        user.votes = orderedVotes;
    };

    /**
     * Handle the notifications to send
     *
     * @param  {String}     widgetId    Widget identifier
     * @param  {String}     type        Notification type
     */
    var handleNotifications = function (widgetData, type) {

        var alreadySend = false;
        var notificationType = '';

        // We do not send notifications on update from public users
        if (!widgetData.loodleData.currentUser.status === 'temporary') {

            $.each(notifications, function (key, isAlreadySend) {
                if (key === type) {
                    if (isAlreadySend) {
                        alreadySend = true;
                    } else {
                        notifications[key] = true;
                        notificationType = key;
                    }
                }
            });

            if (!alreadySend) {
                oae.api.doodle.sendNotifications(widgetData.id, notificationType, function (err) {
                    if (err) {
                        console.log('An error occured : ', err);
                        oae.api.util.notification(
                            oae.api.i18n.translate('__MSG__DOODLE_NOTIFICATIONS_NOT_SENT__', 'doodle'),
                            oae.api.i18n.translate('__MSG__DOODLE_NOTIFICATIONS_COULD_NOT_BE_SENT__', 'doodle'));
                    }
                });
            }

        }

    };

    /**
     * Update the view of the loodle with the current loodle data
     *
     * @param  {Object}     widgetData      Widget data
     * @param  {String}     locale          Language currently use by the user
     */
    var updateLoodleDisplay = function (widgetData, locale) {

        console.log('updateLoodleDisplay');

        oae.api.doodle.getData(widgetData.loodleData.id, function (err, loodle) {

            console.log('loodle : ', loodle);

            if (err) {
                console.log('An error occured trying to get the loodle data : ', err);
                oae.api.util.notification(
                    oae.api.i18n.translate('__MSG__UNEXPECTED_ERROR__', 'doodle'),
                    oae.api.i18n.translate('__MSG__DOODLE_DISPLAY_COULD_NOT_BE_UPDATED__', 'doodle'));
                return;
            }

            // Sort the users array so that the current user always has his name at the bottom of the table
            var index = 0;
            var currentUser = {};
            for (var i = 0; i < loodle.users.length; i++) {
                if (loodle.users[i].id == widgetData.loodleData.currentUser.id) {
                    index = i;
                    currentUser = loodle.users[i];
                }
            }


            loodle.users.splice(index, 1);
            loodle.users.push(currentUser);

            // We keep a trace of the current user
            loodle.currentUser = widgetData.loodleData.currentUser;

            // Format loodle data to easily display
            formatSchedules(loodle, oae.data.me.locale);
            formatUsers(loodle);
{'fraction_non_alphanumeric': 0.1116943866943867, 'fraction_numerical': 0.0037941787941787944, 'mean_word_length': 1.5327102803738317, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '4542605', 'n_tokens_mistral': 5265, 'n_tokens_neox': 4876, 'n_words': 1407}