require('dotenv').load();
var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var _ = require('lodash');
var CronJob = require('cron').CronJob;
var log = require('log-to-file-and-console-node');
var MessageController = require('./controller/message');
var TelegramBot = require('node-telegram-bot-api');

var app = express();
var bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, {polling: true});

var connectionString = '127.0.0.1:27017/telegram-jung2-bot';
if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD){
  connectionString = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' +
    process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
    process.env.OPENSHIFT_APP_NAME;
}
mongoose.connect(connectionString);

app.use(morgan('combined', {'stream': log.stream}));
app.use(bodyParser.json());

var getTopTen = function(chatId) {
  MessageController.getTopTen(chatId, function (err, topTens) {
    if (err) {
      log.e('err: ' + JSON.stringify(err));
      bot.sendMessage(chatId, '[Error] ' + err.message);
    } else {
      var message = 'Top 10 冗員 in the last 7 days:\n';
      message += '\n';
      for (var i = 0, l = topTens.length; i < l; i++) {
        message += topTens[i].firstName + ' ' + topTens[i].lastName + ' ' + topTens[i].percent + '\n';
      }
      bot.sendMessage(chatId, message);
    }
  });
};
bot.onText(/\/topTen/, function (msg, match) {
  log.i('/topTen: ' + JSON.stringify(msg));
  getTopTen(msg.chat.id.toString());
});

bot.on('message', function (msg) {
  log.i('msg: ' + JSON.stringify(msg));
  MessageController.addMessage(msg, function (err) {
    if (err) {
      log.e('err: ' + JSON.stringify(err));
      bot.sendMessage(msg.chat.id, '[Error] ' + err.message);
    }
  });
});

app.route('/')
  .get(function (req, res) {
    res.json({
      status: 'OK',
      desc: 'For UpTimeRobot'
    });
  });

if (process.env.DEFAULT_CRON_JOB_GROUP_ID) {
  var job = new CronJob({
    cronTime: '00 00 18 * * 1-5',
    onTick: function() {
      getTopTen(process.env.DEFAULT_CRON_JOB_GROUP_ID);
    },
    start: false,
    timeZone: 'Asia/Hong_Kong'
  });
  job.start();
}

module.exports = app;
@@ -1256,24 +1256,41 @@
 7 days:%5Cn';%0A
+      var total;%0A
       messag
@@ -1296,24 +1296,24 @@
 ge += '%5Cn';%0A
-
       for (v
@@ -1352,24 +1352,58 @@
 %3C l; i++) %7B%0A
+        total = topTens%5Bi%5D.total;%0A
         mess
@@ -1501,16 +1501,91 @@
       %7D%0A
+      if (total) %7B%0A        message += '%5CnTotal message: ' + total;%0A      %7D%0A
       bo
@@ -2280,24 +2280,96 @@
 unction() %7B%0A
+      bot.sendMessage(process.env.DEFAULT_CRON_JOB_GROUP_ID, '%E5%A4%A0%E9%90%98%E6%94%B6%E5%B7%A5~~');%0A
       getTop

add extra message and reminder message for cron job