#!/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, sys

from dqc_wrapper.utils.utils_db import *
from dqc_downloader.utils_download import *
from dqc_wrapper.utils.utils_files import *

## TODO: test -> pip install ..; python download_workflow.py ../dqc_wrapper/QAR_dqc/conf/ /data/cds-forms-c3s ../dqc_workflow/database/dqc_workflow.db
def main(args):

    # Check parameters
    if len(args) != 3:
        print('Usage: python download_workflow.py <DQC_CONF_DIR> <CDS_FORMS_DIR> <DQC_DB_FILE>')
        return -1
    else:
        dqc_conf_dir = args[0]
        cds_forms_dir = args[1]
        dqc_db_file = args[2]

    # Create connection to SQLITE file
    current_dir = os.path.dirname(os.path.realpath(__file__))
    conn = create_connection(dqc_db_file)

    # LOOP 1: All datasets registered in the database
    for d in select_datasets(conn):

        # Read configuration and check mandatory fields in the general section
        conf_path = os.path.join(dqc_conf_dir, d[0] + '.ini')
        conf = CheckerConfig(conf_path)
        conf.read_config(execute=False)

        # Select remaining downloads
        for dwn in select_required_downloads(conn, d):
            print(dwn)

if __name__ == "__main__":
    args = sys.argv[1:]
    sys.exit(main(args))