"use strict";

const moment = require('moment');
const elasticsearch = require('elasticsearch');

const esClient = new elasticsearch.Client({
  host: 'localhost:9200'
  //host: 'tea-elasticsearch:9200'

});

const INDEX_NAME = 'bigbrother';
const MESSAGE_TYPE_NAME = 'message';

module.exports = {
  getMessage(id) {
    return new Promise((resolve, reject) => {
      esClient.get({
        index: INDEX_NAME,
        type: MESSAGE_TYPE_NAME,
        id: id
      }, function (error, res) {
        if (error) {
          return reject(error);
        }
        res['_source']['date'] = "2016-12-20T13:14:36.629890+00:00";
        resolve(res);
      });
    });
  },

  saveMessage(message) {
    return new Promise((resolve, reject) => {
      esClient.index({
        index: INDEX_NAME,
        type: MESSAGE_TYPE_NAME,
        body: message
      }, (error, response) => {
        if (error) {
          return reject(error);
        }
        resolve(response);
      });
    });
  },

  globalSearch(query, limit) {
    limit = limit || 10;
    return new Promise((resolve, reject) => {
      esClient.search({
        index: INDEX_NAME,
        q: query,
        size: limit
      }, (error, response) => {
        if (error) {
          return reject(error);
        }
        resolve(response.hits);
      });
    });
  },

  buildDialogFromMessageId(messageId) {
    return this.getMessage(messageId).then(message => {
      const messageDate = moment(message.date);
      return esClient.search({
        index: INDEX_NAME,
        query: {
          "bool": {
            "must": [
              {
                "term": {
                  "room": message.room
                }
              },
              {
                "range" : {
                  "date" : {
                    "gte" : messageDate.subtract(2, 'minutes').toISOString(),
                    "lt" : messageDate.add(4, 'minutes').toISOString(),
                    "format": "date_time"
                  }
                }
              }
            ]
          }
        }
      });
    }).then(results => results.hits);
  },

  searchTerm(term) {
    return esClient.search({
      index: INDEX_NAME,
      q: term,
      size: 10
    }).then(resp => {
      var hits = resp.hits.hits;
      if (hits.length === 0) {
        return `Désolé aucun résultat ne correspond à votre recherche "${term}"`;
      } else {
        var nbResults = resp.hits.total;
        if (nbResults > 10) {
          var content = `Voici les 10 premiers résultats de votre recherche "${term}" :<br/>`;
        } else {
          var content = `Voici les ${nbResults} résultats de votre recherche "${term}" :<br/>`;
        }

        hits = hits.map(hit => {
          var message = hit._source.message.replace(term, '<b>' + term + '</b>');
          var date = new Date(hit._source.date);

          return `<td>${hit._source.author} <i>(@${hit._source.username})</i></td>
<td>${date.toUTCString()}</td>
<td>${message}</td>`;
        });
        content += `<table><tr>${hits.join('</tr><tr>')}</tr></table>`;
        return content;
      }
    }, err => {
      console.trace(err.message);
      return `Une erreur est survenue :( => ${err.message}`;
    });
  }
};

@@ -272,16 +272,66 @@
 sage';%0A%0A
+const DATE_FORMAT = %22yyy-MM-dd'T'HH:mm:ss.SSSZ%22;%0A%0A
 module.e
@@ -602,77 +602,8 @@
   %7D%0A
-        res%5B'_source'%5D%5B'date'%5D = %222016-12-20T13:14:36.629890+00:00%22;%0A
     
@@ -1444,21 +1444,35 @@
 (message
-.
+%5B'_source'%5D%5B'
 date
+'%5D
 );%0A     
@@ -1662,13 +1662,27 @@
 sage
-.
+%5B'_source'%5D%5B'
 room
+'%5D
 %0A   
@@ -1845,36 +1845,42 @@
  'minutes').
-toISOString(
+format(DATE_FORMAT
 ),%0A         
@@ -1931,20 +1931,26 @@
 s').
-toISOString(
+format(DATE_FORMAT
 ),%0A 

Format date with correct format