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

from zipfile import ZipFile

'''
Script in order to rename pdf to the changing conventions of C3S
'''
# Folder with results
res_folder = '.'
ds_names = {
    'reanalysis-era5-land-monthly-means': 'reanalysis_era5_land_monthly_means-era5_land',
    'reanalysis-era5-single-levels-monthly-means': 'reanalysis_era5_single_levels_monthly_means-era5',
    'reanalysis-era5-pressure-levels-monthly-means': 'reanalysis_era5_pressure_levels_monthly_means-era5',
    'reanalysis-uerra-europe-pressure-levels': 'reanalysis_uerra_europe_pressure_levels',
    'reanalysis-uerra-europe-single-levels': 'reanalysis_uerra_europe_single_levels',
    'seasonal-monthly-single-levels': 'seasonal_monthly_single_levels',
    'seasonal-original-single-levels': 'seasonal_original_single_levels',
    'seasonal-monthly-pressure-levels': 'seasonal_monthly_pressure_levels',
    'seasonal-original-pressure-levels': 'seasonal_original_pressure_levels',
    'seasonal-postprocessed-pressure-levels': 'seasonal_postprocessed_pressure_levels',
    'seasonal-postprocessed-single-levels': 'seasonal_postprocessed_single_levels',
    'reanalysis-era5-single-levels': 'reanalysis_era5_single_levels-era5',
    'reanalysis-era5-pressure-levels': 'reanalysis_era5_pressure_levels-era5'
}

for zip_file in sorted(glob.glob(os.path.join(res_folder, '*.zip'))):

    print(zip_file)
    file_list = []

    try:
        # Input
        with ZipFile(zip_file, 'r') as zipf:

            # Zipf
            out_file = None
            for k, v in ds_names.items():
                if k in zip_file:
                    out_file = zip_file.replace(k, v)
                    key = k
                    val = v

            if out_file is None:
                continue

            # Contents
            zipf.extractall()
            contents = zipf.namelist()
            for cont in contents:
                dest = cont.replace(key, val)
                file_list.append(dest)
                os.system('mv {} {}'.format(cont, dest))

            print(out_file)

            # Unzip to /tmp
            print('--------------------')

        # Output
        with ZipFile(out_file, 'w') as zipf:
            for f in file_list:
                zipf.write(f, os.path.basename(f), compress_type=zipfile.ZIP_DEFLATED)
                os.unlink(f)

        # Delete original
        os.unlink(zip_file)
    except:
        pass