#!/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)
#

from dqc_wrapper.utils.utils_pdf import *
from dqc_wrapper.utils.utils_files import *

'''
Read a configparser object
'''
def read_conf_file(res_file):
	config = configparser.RawConfigParser()
	config.read(res_file)
	return config

'''
Get latest log file
'''
def get_log_file(log_folder, res_file):
	# Get latest available log file
	log_files = sorted(
		glob.glob(os.path.join(log_folder, 'LOG_{}*.txt'.format(os.path.basename(res_file)))),
		reverse=True,
	)
	return log_files[0]

'''
INI format to PDF
'''
def ini2pdf(res_file, log_file):

	# Zip
	zipfname = res_file.replace('.ini', '.zip')
	files2zip = []

	# Res file  
	config = read_conf_file(res_file)

	# Save PDF report (result + log)
	if os.path.exists(log_file):
		for s in config.sections():
			if not('result' in s):
				pdf_file = save_pdf_report(s, res_file, log_file)
				files2zip.append(pdf_file)
				if 'valid_ranges' in pdf_file:
					html_file = pdf_file.replace('.pdf', '.html')
					files2zip.append(html_file)
	else:
		print('ERROR: Missing log file {}'.format(log_file))

	zip_results(zipfname, files2zip)

'''
INI format to PDF
'''
def ini2pdf_justheader(res_file):

	# Res file
	config = read_conf_file(res_file)

	# Save PDF report (result + log)
	for s in config.sections():
		if not('result' in s):
			pdf_file = save_pdf_report(s, res_file, None)

	return pdf_file

'''
Script in order to convert res and log files to separate PDFs to be imported at the CDS / CMS
'''
# Folder with results
res_folder = '/shared/QAR_dqc/results'
log_folder = '/tmp/logz'
just_header = True

for res_file in glob.glob(os.path.join(res_folder, '*.ini')):
	print('------------------------')
	print('INI: ' + res_file)
	print('------------------------')
	if just_header:
		pdf_file = ini2pdf_justheader(res_file)
	else:
		log_file = os.path.join(log_folder, get_log_file(log_folder, res_file))
		print('LOG: ' + log_file)
		pdf_file = ini2pdf(res_file, log_file)
	print('PDF: ' + pdf_file)