const admin = require('firebase-admin');
const getServiceAccount = require('../lib/google');

const serviceAccount = getServiceAccount();

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

const db = admin.firestore();

module.exports.log = function(msg) {
  const type = msg.message.text.split(' ')[1];
  const timeInMilli = new Date().getTime().toString();
  const docRef = db.collection(type).doc(timeInMilli);

  docRef.set({
    id: msg.message.id,
    user: msg.message.user.name,
    command: msg.message.text,
    room: msg.message.room
  });
};

module.exports.tail = function(msg) {
  const textArray = msg.message.text.split(' ');

  // Type will alsways be the last argument
  const type = textArray[textArray.length - 1];

  // Calcualte the index of -n flag
  const indexOfN = textArray.indexOf('-n');
  const limit = indexOfN === -1 ? 10 : parseInt(textArray[indexOfN + 1]);

  db.collection(type)
    .limit(limit)
    .get()
    .then(req => {
      req.forEach(doc => {
        const dateInMilli = parseInt(doc.id);
        const dateString = new Date(dateInMilli).toLocaleString('no', {
          hour12: false
        });
        console.log('Doc', doc);
        msg.send(dateString, doc.data());
      });
    })
    .catch(err => {
      msg.send('Error getting documents', err);
    });
};

@@ -464,22 +464,29 @@
 id: 
-msg.message.id
+parseInt(timeInMilli)
 ,%0A  
@@ -942,16 +942,43 @@
 n(type)%0A
+    .orderBy('id', 'desc')%0A
     .lim
@@ -1013,24 +1013,50 @@
 en(req =%3E %7B%0A
+      let response = '';%0A%0A
       req.fo
@@ -1224,24 +1224,25 @@
     %7D);%0A
+%0A
         
 console.
@@ -1237,82 +1237,178 @@
     
-console.log('Doc', doc);%0A        msg.send(dateString, doc.data());%0A      %7D
+response += %60At: $%7BdateString%7D, %5B$%7Bdoc.data().user%7D%5D said %5B$%7B%0A          doc.data().command%0A        %7D%5D in room %5B$%7Bdoc.data().room%7D%5D %5Cn%60;%0A      %7D);%0A%0A      msg.send(response
 );%0A 
@@ -1439,24 +1439,27 @@
 %7B%0A      
-msg.send
+console.log
 ('Error 

Format tail response