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


'''
Script in order to rename pdf to the changing conventions of C3S
'''
# Folder with results
res_folder = '/shared/QAR_dqc/results'
conf_folder = '/data/joan/c3s512-wp1-datachecker/dqc_wrapper/QAR_dqc/conf'
out_folder = '/shared/QAR_dqc/results_cms'

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

    try:
        # Configuration file
        conf_file = os.path.join(conf_folder, os.path.basename(zip_file).replace('.zip', '.ini'))
        config = configparser.ConfigParser()
        config.read(conf_file)

        # Find cms_name
        key = os.path.basename(zip_file).replace('.zip', '')
        val = config['general']['cms_name']
        out_file = os.path.join(out_folder, os.path.basename(zip_file.replace(key, val)))
        file_list = []

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

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

        # Output
        with zipfile.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)
                os.unlink(f.replace(val,key))
                print(f)
            print(out_file)
            print('----------------')

    except:
        print('WARNING: problems opening file {}'.format(zip_file))
        pass