#!/usr/bin/env node

var http = require('http');
var clc = require('cli-color');
var clc_color = require('./lib/clc-color');

var id_color = clc.xterm(232).bgWhiteBright;
var def_source_color = clc.whiteBright.bgXterm(232);

var config = require('./cfg/config_cl.json');
var htpasswd = require('./cfg/htpasswd.json');

var get_n = process.argv[2];
var path;
if (get_n)
	path = '/' + get_n;
else
	path = '/getprev/' + config.num_notifications;

var options = {
	hostname: config.host,
	port: config.port,
	path: path,
	method: 'GET',
	auth: htpasswd.username + ':' + htpasswd.password
};

var printNotification = function(notification) {
	var source_color = def_source_color;
	if(notification.colorfg)
		source_color = clc_color.color_from_text(notification.colorfg, notification.colorbg);

	// if the string is wider than our terminal we need to shorten it
	var source_text_length = 5 + notification.id.length + notification.source.length;
	var text_length = notification.text.length;
	if(source_text_length + text_length > process.stdout.columns)
		notification.text = notification.text.substr(0, process.stdout.columns - source_text_length - 3) + '...';

	console.log(id_color(' ' + notification.id + ' ') + source_color(' ' + notification.source + ' ') + ' ' + notification.text);
};

var req = http.request(options, function(res) {
	var contentLength = res.headers['content-length'];
	var data = "";

	res.on('data', function(chunk) {
		if(res.statusCode !== 200) {
			console.log("Notification not found.");
			return;
		}

		data += chunk;

		// do we have all data?
		if (chunk.length >= contentLength) {
			var json_data = JSON.parse(data);

			if (get_n) // requested only a specific notification
				printNotification(json_data);
			else // got an array of notifications
				for(var i = 0; i < json_data.length; i++)
					if(json_data[i])
						printNotification(json_data[i]);
		}
	});
});

req.end();

@@ -164,16 +164,49 @@
 Bright;%0A
+var date_color = clc.xterm(242);%0A
 var def_
@@ -816,16 +816,100 @@
 orbg);%0A%0A
+%09var date_string = new Date(notification.date).toTimeString().split(' ')%5B0%5D + ' ';%0A%0A
 %09// if t
@@ -1048,16 +1048,37 @@
 e.length
+ + date_string.length
 ;%0A%09var t
@@ -1301,16 +1301,42 @@
 ole.log(
+date_color(date_string) + 
 id_color
@@ -1514,16 +1514,25 @@
 ength = 
+parseInt(
 res.head
@@ -1552,16 +1552,17 @@
 length'%5D
+)
 ;%0A%09var d
@@ -1746,21 +1746,20 @@
 ?%0A%09%09if (
-chunk
+data
 .length 

fix typo and add date strings