from django.core.management.base import BaseCommand, CommandError
from catalog.models import User, News, Publisher, Topic, audioTime, Search
from django.db.models import Q
import os
import json

class Command(BaseCommand):
	help = 'Report database'


	def add_arguments(self, parser):
		parser.add_argument('json', nargs=1, type=str) #(options['basedir'][0]

	def handle(self, *args, **options):
		data = dict()
		data['users'] = User.objects.all().count()
		data['publishers'] = Publisher.objects.all().count()
		data['text'] = Publisher.objects.all().filter(type="texto").count()
		data['audio'] = Publisher.objects.all().filter(type="audio").count()
		data['documents'] = News.objects.all().count()
		data['searches'] = Search.objects.all().count()

		print ( "Users: " + str(User.objects.all().count()) )
		print ( "Publishers: " + str(Publisher.objects.all().count()) )
		print ( "\tText: " + str(Publisher.objects.all().filter(type="texto").count()) )
		print ( "\t\tDocuments: " + "{:,}".format(News.objects.all().count()) )
		print ( "\tAudio: " + str(Publisher.objects.all().filter(type="audio").count()) )
		print ( "Busquedas: " + str(Search.objects.all().count()) )


		minutes = sum([a.minutes for a in audioTime.objects.all()])
		print ( "\t\tRecorders hours: " + "{:,}".format(minutes/60.) )

		print("=======================================================")
		textSources = Publisher.objects.all().filter(type="texto")
		for t in textSources:
			if News.objects.all().filter(publisher=t).count() <= 0:
				continue
			newsP=News.objects.all().filter(publisher=t).order_by("date")
			count = str(newsP.count()) 
			date =  newsP[0].date.date().strftime('%m/%d/%Y')
			print(t.name + ", " + t.url + ", " + str(newsP.count()) +", "+ newsP[0].date.date().strftime('%d/%m/%Y') ) 
		print("=======================================================")
		audioSources = Publisher.objects.all().filter(type="audio")
		data["audioTime"]=0
		for a in audioSources:
			if audioTime.objects.all().filter(publisher=a).count() <=0:
				print ("No adutioTime for: ", a)
			else:
				minutes = audioTime.objects.all().filter(publisher=a)[0].minutes
				print(a.name + ", " + a.url + ", " + str(minutes))  
				data["audioTime"]+=minutes
		print(data)
		with open(options['json'][0], 'w') as outfile:
			outfile.write("m3Data="+json.dumps(data)+";")
			outfile.close()
