#!/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 glob
import os

'''
Script run in order merge monthly and daily pdfs
'''
csv_dir = '/shared/QAR_dqc/results'

for monthly_pdf in glob.glob(os.path.join(csv_dir, '*monthly*.pdf')):
    if 'file_format' in monthly_pdf or 'standard_compliance' in monthly_pdf:

        # Seasonal
        if 'seasonal-monthly-single-levels' in monthly_pdf:
            daily_pdf = monthly_pdf.replace('monthly', 'original')
            out_name = monthly_pdf.replace('seasonal-monthly-single-levels', 'seasonal_original_single_levels-seasonal_monthly_single_levels')
        if 'seasonal-monthly-pressure-levels' in monthly_pdf:
            daily_pdf = monthly_pdf.replace('monthly', 'original')
            out_name = monthly_pdf.replace('seasonal-monthly-pressure-levels', 'seasonal_original_pressure_levels-seasonal_monthly_pressure_levels')

        # Reanalysis-era5
        if 'reanalysis-era5-single-levels-monthly-means' in monthly_pdf:
            daily_pdf = monthly_pdf.replace('-monthly-means', '')
            out_name = monthly_pdf.replace('reanalysis-era5-single-levels-monthly-means', 'reanalysis_era5_single_levels-reanalysis_era5_single_levels_monthly_means-era5')
        if 'reanalysis-era5-pressure-levels-monthly-means' in monthly_pdf:
            daily_pdf = monthly_pdf.replace('-monthly-means', '')
            out_name = monthly_pdf.replace('reanalysis-era5-pressure-levels-monthly-means', 'reanalysis_era5_pressure_levels-reanalysis_era5_pressure_levels_monthly_means-era5')

        # Reanalysis-land
        if 'reanalysis-era5-land-monthly-means' in monthly_pdf:
            daily_pdf = monthly_pdf.replace('-monthly-means', '')
            out_name = monthly_pdf.replace('reanalysis-era5-land-monthly-means', 'reanalysis_era5_land-reanalysis_era5_land_monthly_means-era5')

        # Let's merge if we can
        if os.path.exists(daily_pdf) and os.path.exists(monthly_pdf):
            cmd = 'pdfunite {d} {m} {o}'.format(d=daily_pdf, m=monthly_pdf, o=out_name)
            print(daily_pdf)
            print(monthly_pdf)
            print(out_name)
            os.system(cmd)
            print('------')