#!/usr/bin/env python
#
# Data Quality Checker also known as DQC
#
# Read the README.md for more detailed information
#
#       Barcelona Supercomputing Center - Centro Nacional de Supercomputacion
#       Earth Sciences Department - Computational Earth Sciences
#     
#     Authors: 
#       Joan Sala Calero (joan.sala@bsc.es)

import os

import configparser
from io import StringIO

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, landscape, A4
from reportlab.lib.units import inch, cm

"""
Convert a txt to a pdf file (reporting)
"""
def save_pdf_report(testname, res_file, log_file):

	# PDF report name
	pdf_file = res_file.replace('.ini', '-{}.pdf'.format(testname))
	print('INFO: Saving report to {}'.format(pdf_file))

	# Read+Filter content (result/config)
	res_str = filter_config(res_file, testname)

	# Read content (detailed log file messages)
	log_str = ''
	with open(log_file, 'r') as f2:
		log_str = f2.read()
		log_str = filter_page(testname, log_str)

	# Write PDF
	try:
		# Init		
		c = canvas.Canvas(pdf_file)
		
		# Write 2 sections	
		break_into_pages(res_str, c, 8, 70)
		break_into_pages(log_str, c, 5, 100)
		
		# Save
		c.save()		
	except:
		raise Exception('Could not convert txt to pdf. Check directory permissions')

"""
Filter a config object
"""
def filter_config(res_file, testname):
	cf = configparser.ConfigParser()
	cf.read(res_file)

	for s in cf.sections():
		if not(testname in s):
			cf.remove_section(s)
	
	res_str = StringIO()		
	cf.write(res_str)
	return res_str.getvalue()	

"""
Filter page (by test name)
"""
def filter_page(s, page_str):
	out_str = ''
	s1 = s.replace('-', '_')
	s2 = s.replace('_', '-')

	for l in page_str.splitlines():	
		iden = l.split(':')[0]
		if s1 in iden or s2 in iden or s in iden:
			out_str += (l + '\n')
	return out_str

"""
Init PDF page
"""
def init_page(c, font_size):	
	t = c.beginText()		
	t.setFont('Courier', font_size)
	t.setCharSpace(0.5)
	t.setTextOrigin(40, 800)
	return t

"""
Write PDF page
"""
def write_page(c, t, font_size):
	imgdir = os.path.dirname(os.path.realpath(__file__))	
	c.drawImage(os.path.join(imgdir, "header.png"), 0, 0, mask='auto', height=0.75*inch, width=8.5*inch)
	c.drawText(t)
	c.showPage()
	return init_page(c, font_size)

"""
Write a string into pages
"""
def break_into_pages(txtstr, c, font_size, lines_per_page):
	
	t = init_page(c, font_size)
	count_lines = 0

	for l in txtstr.split('\n'):
		if count_lines == lines_per_page:
			t = write_page(c, t, font_size)
			count_lines = 0
		else:
			t.textLine(l)
			count_lines+=1

	# Last page
	if count_lines != 0:
		write_page(c, t, font_size)
