
$(document).ready(function(){
	$('#loading').hide()

	$('#info').click( function() {
		console.log("click");
		$('#info-search').toggle();
	});

	$('#search').submit(function(e) {
		e.preventDefault();
		args = $(this).serialize();	
		$('#graph').empty();
		$('#results').empty();		

		console.log('/search?'+ args)

		$('#loading').show()
		$.get('/search?'+ args, function(data) {
			$('#loading').hide()
			console.log(data);
			// $('#graph').empty();
			// $('#results').empty();
			$.each(data.result, function(i, item) {
				search_result_archive(item, data.tags);
			});
			graph(data);		
		});
	});

});

function search_result_archive(a, tags) {	

	// aaa = '<aaa class="aaa">[net.art]</aaa> <aaa class="aaa">[net history]</aaa> <aaa class="aaa">[end2end]</aaa>'
	aaa = ''
	for(let t of tags) {
		aaa += '<aaa class="aaa">[' + t + ']</aaa> '
	}

	$('<div/>', {
		id: a.archive,
		class: "archive",
	}).appendTo('#results');
	$('#' + a.archive).append("<h3>" + a.archive + "</h3>");
	$.each(a.results, function(i, r) {
		$('<ul/>', {
			id: r.thread + "-" + a.archive,
			text: r.thread.replace('_', ' ')
		}).appendTo('#' + a.archive);
		let hits = "<ul>";
		
		$.each(r.hits, function(j, h){
			// console.log(h)
			let hit = '<li><a href="' + h.url+ '" target="_blank">' + h.subject + '</a> -- <i>' + h.author_name + '</i>';
			if (h.hasOwnProperty('sel')) {
				hit += ' <bb class="bb">[' + h.sel + ']</bb>'
			} else {
				hit += ' <aa class="aa" data-list="' + a.archive + '" data-url="' + h.url + '"> (+) ' + aaa + '</aa></li>';
			}
			hits += hit;
		});
		hits += "</ul>";
		$('#' + r.thread + "-" + a.archive).append(hits);
	});
	$(".aa").click(function(e) {
		e.stopImmediatePropagation();
		$(this).children().toggle();
	});
	$(".aaa").hide();
	$(".aaa").click(function(e) {
		e.stopImmediatePropagation();

		let p = $(this).parent();
		console.log("click : " + p.data("list") + " -- " + p.data("url") + " -- " + $(this).text());
		tag = $(this).text().replace('[','').replace(']', '');

		// collect (url, tags, list)
		args =  'url=' + encodeURIComponent(p.data("url")) + '&tags=' + encodeURIComponent(tag) + '&list=' + encodeURIComponent(p.data("list"))

		$.get('/collect?'+ args, function(data) {

			console.log(data)

			$.each(data.commited, function(i, r) {
				aa = $('aa[data-url="'+r+'"]') 
				p = aa.parent();
				aa.remove();
				p.append(' <bb class="bb">[' + data.tag + ']</bb>')
			});
			
		});
		
	});


}

var min_month = new Date(1995, 9);
var max_month = new Date();

function diff_months(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth();
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}

function format(date) {
  var month_names = [
    "Jan", "Feb", "Mar",
    "Apr", "May", "Jun", "Jul",
    "Aug", "Sep", "Oct",
    "Nov", "Dec"
  ];
  return month_names[date.getMonth()] + ' ' + date.getFullYear();
}


function graph(data) {
	var d = diff_months(min_month, max_month);
	var vec = new Array();
	for(let ar of data.result) {
		let ar_vec = new Array(d + 1).fill(0);
		ar_vec[0] = ar.archive;
		for(let r of ar.results) {
			let date = new Date(Date.parse(r.thread.replace("_", " 1, "))); // this may blow...
			let index = diff_months(min_month, date);
			ar_vec[index  + 1] = r.nbr_hits;
		}
		vec.push(ar_vec);
	}
	
	var x_axis = new Array(d);
	for (let i = 0; i < d; i++) {
		let d = new Date(min_month.getFullYear(), min_month.getMonth());
		d.setMonth(d.getMonth() + i);
		x_axis[i] = format(d);
	}


	// console.log(vec);

	var chart = c3.generate({
	    bindto: '#graph',	    
	    data: {
	      	columns: vec,
	      	type: 'bar'
	    },
	    axis: {
	    	x: {
	    		type: 'category',
	    		categories: x_axis,
	    		tick: {
	    			culling: {
	    				max: 15
	    			},
	    			multiline:false
	    		}
	    	}
	    },
	    bar: {
	        width: {
	            ratio: 0.8
	        }
    	}
	});
}





























