#!/usr/bin/env python

__author__ = 'mathieu@garambrogne.net'

from optparse import OptionParser
import hashlib
import os.path

from collectatrends.collecta import Collecta
from collectatrends.store import DbmStore, mkdir_p
from collectatrends.opensearch import TooManyQuestion

from roundrobin.rrd import create, COUNTER, AVERAGE

if __name__ == '__main__':
	parser = OptionParser()
	parser.add_option("-q", "--query", dest="query", help="collecta query")
	parser.add_option("-f", "--folder", dest="folder", default='~/.collectatrends', help="folder to store trends")

	(options, args) = parser.parse_args()
	c = Collecta(remember=True, cache_folder = options.folder)
	results = c.query(q=options.query)
	h = hashlib.sha1()
	h.update(options.query)
	path = '%s/%s' % (os.path.expanduser(options.folder), h.hexdigest())
	mkdir_p(path)
	d = DbmStore(path)
	try:
		for r in results:
			d[r['id']] = r
	except TooManyQuestion:
		print "Too many questions"
	print len(results), len(d)
	path = '%s/%s.rrd' % (os.path.expanduser(options.folder), h.hexdigest())
	mkdir_p(path)
	rrd = create(path,
		COUNTER(options.query, 600, 'U','U'),
		AVERAGE(0.5, 1, 24),
		AVERAGE(0.5, 6, 10),
		)
	rrd.update([(None, len(d))])