#!/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
from reportlab.pdfgen import canvas

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

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

	# Read content
	tot_str = ''
	with open(res_file, 'r') as f1:
		resstr = f1.read()

	with open(log_file, 'r') as f2:
		logstr = f2.read()


	# Write PDF
	try:
		# Init
		c = canvas.Canvas(pdf_file)	

		# Write 2 sections	
		break_into_pages(resstr, c, 8, 70)
		break_into_pages(logstr, c, 5, 125)
		
		# Save
		c.save()		
	except:
		raise Exception('Could not convert txt to pdf. Check directory permissions')

"""
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):
	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)
