#!/usr/bin/env python
#
# Data Quality Checker also known as DQC
#
# Read the README.md for more detailed information
#
# Barcerlona Supercomputing Center - Centro Nacional de Supercomputacion
#        Earth Sciences Department - Computational Earth Sciences
#     
#     Authors: Ivan Jose Cernicharo Ortiz (ivan.cernicharo@bsc.es)
#             -
#             -
#

import sys
import logging
import datetime
import subprocess
import os

def all_checks():
    return {
        "file_format":"test00_file_format",
        "standard_compliance":"test01_standard_compliance",
        "spatial_completeness":"test02_spatial_completeness",
        "temporal_completness":"test03_temporal_completeness",
        "spatial_consistency":"test04_spatial_consistency",
        "temporal_consistency":"test05_temporal_consistency",
        "valid_ranges":"test06_valid_ranges"
    }

class checker_body:

    def __init__(self,name):
        self.name = name
        self.version = "0.0.1"
        self.help_mssg()

    def __version__(self):
        string = "\nData Quality Checker Wrapper Version: " + self.version + "\n"
        print(string)

    def help_mssg(self):
        string = "\n#"+ "#" * 80 + "\n#\n"
        string += "#"+ " " * 2+"Data Quality Checker Help message - How to run the DQC:\n#\n"
        string += "#"+ " " * 4+"$ python checker.py --test <type of test> [[other arguments in function of the test]] --input <file or folder>\n#\n"
        string += "#\tType of tests available: file_format\n"
        string += "#\t                         standard_compliance\n"
        string += "#\t                         spatial_completeness\n"
        string += "#\t                         temporal_completeness\n"
        string += "#\t                         spatial_consistency\n"
        string += "#\t                         temporal_consistency\n"
        string += "#\t                         valid_ranges\n#\n"
        string += "#"+ " " * 4+"Some of these tests needs additional arguments as listed below:\n#\n"
        string += "#\t1. If <type of test> == file_format\n"
        string += "#"+ " " * 2+"$ python checker.py --test file_format --input <file or folder>\n#\n"
        string += "#\t2. If <type of test> == standard_compliance\n"
        string += "#"+ " " * 2+"$ python checker.py --test standard_compliance --type <e.g.: seasonal_grib,seasonal_netcdf, cmip5 netcdf,...> --input <file or folder>\n#\n"
        string += "#\t3. If <type of test> == spatial_completeness\n"
        string += "#"+ " " * 2+"$ python checker.py --test spatial_completeness --type <e.g.: netcdf, grib> --input <file or folder>\n#\n"
        string += "#\t4. If <type of test> == temporal_completeness\n"
        string += "#"+ " " * 2+"$ python checker.py --test temporal_completeness --temporal_range <time interval(e.g.: 1979-01-01/2019-05-01)> --input <file or folder>\n#\n"
        string += "#\t5. If <type of test> == spatial_consistency\n"
        string += "#"+ " " * 2+"$ python checker.py --test spatial_consistency --type <e.g.: netcdf, grib> --space_interval <spatial grid(e.g.: 1 degree)> --input <file or folder>\n#\n"
        string += "#\t6. If <type of test> == temporal_consistency\n"
        string += "#"+ " " * 2+"$ python checker.py --test temporal_consistency --type <e.g.: netcdf, grib> --time_interval <e.g.: 1 hourly, 6 hourly, daily, monthly> --input <file or folder>\n#\n"
        string += "#\t7. If <type of test> == valid_ranges\n"
        string += "#"+ " " * 2+"$ python checker.py --test valid_ranges --type <e.g.: netcdf, grib>--var <variable (i.e.: tas, 2mt, t,..)> --input <file or folder>\n#\n"
        string += "#" + "#" * 80 + "\n"

        self.help = string

def main(args):
    dqc = checker_body("testing")
    dqc.__version__()

    try:
        conditional1 = (args[0] != "--test" and (args[2] == "--input" or args[4] == "--input"))
        conditional2 = (args[0] in ["--help","-h","help","sos","commands"])

    except:
        print(dqc.help)
        sys.exit()
    
    if conditional1 or conditional2:
        print(dqc.help)
        sys.exit()

    if args[1] not in all_checks().keys():
        print(dqc.help)
        sys.exit()

    if not conditional1 and not conditional2:
        if args[6] == "--time_interval":
            time_interval = args[7]


        if args[3] == "--log_output_dir":
            path_logs = args[4]

        if args[2] == "--input":
            path_files = args[3]

        elif args[3] == "--input":
            path_files = args[4]
        
        elif args[4] == "--input":
            path_files = args[5]

        elif args[5] == "--input":
            path_files = args[6]

        elif args[6] == "--input":
            path_files = args[7]

        if args[1] == 'file_format':
            import test00_file_format
            file_format_check = test00_file_format.file_format_check(path_files)
            print(file_format_check.return_extensions_format())

        if args[1] == 'standard_compliance' and args[2] == '--type':
            import test01_standard_compliance as test
            standard_ck = test.standard_compliance_test(
                path_files,
                args[3]
            )
            standard_ck.main()
            
        if args[1] == 'spatial_completeness' and args[2] == '--type':
            import test02_spatial_completeness as test
            spatial_completeness_ck = test.spatial_completeness_test(
                path_files,
                args[3]
            )
            spatial_completeness_ck.main()

        if args[1] == 'temporal_completeness' and args[2] == '--type':
            import test03_temporal_completeness as test
            temporal_completeness_ck = test.spatial_completeness_test()
            # TO BE FINISHED
            #temporal_completeness_ck.main()

        if args[1] == 'spatial_consistency':
            with open(os.devnull, 'w') as fp:
                subprocess.Popen(['utils/check_spatial_consistency.bash %s %s %s'%(args[3], args[5], args[7])], shell=True,stderr=fp)
#            import test04_spatial_consistency as test
#            spatial_consistency_ck = test.spatial_consistency_test(
#                path_files,
#                args[3]
#            )
#            spatial_consistency_ck.main()

#        if args[1] == 'temporal_consistency' and args[2] == '--type':
        if args[1] == 'temporal_consistency' :
            print('time_interval')
            print(time_interval)
            import test05_temporal_consistency as test
            test.temporal_consistency_test(
                path_files,
                time_interval
            )
            #temporal_consistency_ck.main()

        if args[1] == 'valid_ranges' and args[2] == '--type':
#        if args[1] == 'valid_ranges' :
            import test06_valid_ranges as test
            valid_ranges_ck = test.valid_ranges_test(
                path_files,
                args[3]
            )
            valid_ranges_ck.check(k_sd_REF = 10)

if __name__ == "__main__":
    args = sys.argv[1:]

    sys.exit(main(args))
