//
//   Copyright 2009-2014 Ilkka Oksanen <iao@iki.fi>
//
//   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.
//

'use strict';

const co = require('co'),
      _ = require('lodash'),
      CronJob = require('cron').CronJob,
      redis = require('./redis').createClient(),
      log = require('./log'),
      conf = require('./conf'),
      mailer = require('./mailer'),
      friends = require('../models/friends');

exports.init = function() {
    // Once in an hour
    new CronJob('0 0 */1 * * *', deleteStaleSessions, null, true); // eslint-disable-line no-new
    // Once in 15 minutes
    new CronJob('0 */10 * * * *', deliverEmails, null, true); // eslint-disable-line no-new
};

// Cleans stale sessions that might exist because of server crash
function deleteStaleSessions() {
    log.info('Running deleteStaleSessions job');

    co(function*() {
        let ts = Math.round(Date.now() / 1000) - conf.get('session:idle_timeout');
        let list = yield redis.zrangebyscore('sessionlastheartbeat', '-inf', ts);

        for (let item of list) {
            let fields = item.split(':');
            let userId = fields[0];
            let sessionId = fields[1];

            let last = yield redis.run('deleteSession', userId, sessionId);
            log.info(userId, 'Removed stale session. SessionId: ' + sessionId);

            if (last) {
                yield friends.informStateChange(userId, 'logout');
            }
        }
    })();
}

// Sends email notifications to offline users
function deliverEmails() {
    log.info('Running deliverEmails job');

    function groupNotifications(ntf) {
        return ntf.groupName ? `Group: ${ntf.groupName}` : `1-on-1: ${ntf.senderName}`;
    }

    co(function*() {
        let userIds = yield redis.smembers('emailnotifications');

        for (let userId of userIds) {
            let notificationIds = yield redis.lrange(`emailnotificationslist:${userId}`, 0, -1);
            let notifications = [];

            for (let notificationId of notificationIds) {
                let notification = yield redis.hgetall(`emailnotification:${notificationId}`);

                if (notification) {
                    notifications.push(notification);
                }
            }

            notifications = _.groupBy(notifications, groupNotifications);

            let user = yield redis.hgetall(`user:${userId}`);

            // TBD: Better would be to clear pending notifications during login
            if (parseInt(user.lastlogout) !== 0) {
                mailer.send('emails/build/mentioned.hbs', {
                    name: user.name,
                    notifications: notifications
                }, user.email, `You were just mentioned on MeetAndSpeak`);
            }

            for (let notificationId of notificationIds) {
                yield redis.del(`emailnotification:${notificationId}`);
            }

            yield redis.del(`emailnotificationslist:${userId}`);
            yield redis.srem('emailnotifications', userId);
        }
    })();
}

@@ -813,24 +813,56 @@
 e('./log'),%0A
+      init = require('./init'),%0A
       conf =
@@ -964,16 +964,32 @@
 nds');%0A%0A
+let jobs = %5B%5D;%0A%0A
 exports.
@@ -1031,24 +1031,34 @@
 an hour%0A    
+jobs.push(
 new CronJob(
@@ -1110,39 +1110,10 @@
 rue)
+)
 ;
- // eslint-disable-line no-new
 %0A   
@@ -1139,16 +1139,26 @@
 tes%0A    
+jobs.push(
 new Cron
@@ -1209,39 +1209,96 @@
 rue)
-; // eslint-disable-line no-new
+);%0A%7D;%0A%0Aexports.quit = function() %7B%0A    for (let job of jobs) %7B%0A        job.stop();%0A    %7D
 %0A%7D;%0A

Add quit method to scheduler