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

# Local import
from dqc_wrapper.utils.utils_files import *
from dqc_wrapper.utils.utils_xarray import *
from dqc_wrapper.utils.utils_grib import *

"""
Class: Spatial completeness checks
---
- Checks for data gaps or missing values
"""
class SpatialCompletenessTest:

    def __init__(self, files, varname, dt, cds_dataset, system, origin, masks_dir, lsm):
        self.testid = 'test02-spatial_completeness'
        self.logger = logging.getLogger(self.testid)                  
        self.varname = varname
        self.datatype = dt
        self.files = files
        self.land_sea_mask = (lsm.strip() == 'yes')

        # Mask pattern to find mask files in function of their resolution (depends on dataset)
        if 'seasonal' in cds_dataset:
            self.mask_pattern = os.path.join(masks_dir, '{}-{}-{}-land_sea_mask.grib'.format(cds_dataset, origin, system))
        else:
            self.mask_pattern = os.path.join(masks_dir, '{}-*-land_sea_mask.grib'.format(cds_dataset))
        self.logger.info('Mask pattern: {}'.format(self.mask_pattern))

        # Mask depends on the given dataset (only for ocean and/or land products)
        self.cds_dataset = cds_dataset

        # Get file characteristics (resolution and step) - if GRIB <-> filtering needed (we get the highest resolution)
        self.nbp = []
        self.stp = []
        if '.grib' in files[0] or '.grb' in files[0]:
            self.nbp = grib_get_max_resolution(files[0])
            self.stp = grib_get_stepType(files[0])

    """
    Loop over datatypes, return missing_values/unnecessary_values + error message if any
    """
    def loop_over_datasets(self, ds, mask_files):
        mv = 0
        uv = 0
        for d in ds:
            try:
                if self.land_sea_mask:
                    max_nbp = max(mask_files.keys()) # Get highest resolution mask
                    mvt, uvt = find_missing_unnecessary_values(d, mask_files[max_nbp], self.varname)
                else:
                    mvt, uvt = find_missing_unnecessary_values(d, None, self.varname)
                mv += mvt
                uv += uvt
            except Exception as e:
                return -1, -1, str(e)

        return mv, uv, ''

    """
    Loading DATA | Check for missing values
    Returns -1 if data problems, alongisde with an error message
    """
    def missing_values_xarray(self, filepath, mask_files):

        # Read data into Xarray
        msg = ''
        try:            
            ds = open_dataset(filepath, datatypes=self.datatype, nbpoints=self.nbp, steptypes=self.stp)
        except Exception as e:
            return -1, -1, str(e)

        # Check if there is an ocean mask
        mv, uv, msg = self.loop_over_datasets(ds, mask_files)

        # Remove NaN values + flatten        
        return mv, uv, msg

    """
    Read masks (if needed) - Return an dictionary of all possible resolutions (useful for datatypes)
    """
    def read_masks(self):
        mask_files = {}

        # Only load stuff when needed
        if self.land_sea_mask:

            # Get all possible masks resolutions
            mask_paths = glob.glob(self.mask_pattern)
            try:
                for f in mask_paths:
                    gc = GribFileCheck(f)
                    mask = gc.get_grib_first_values()
                    mask_files[len(mask)] = mask
                    self.logger.info('INFO: {} loaded'.format(os.path.basename(f)))
            except Exception as e:
                return 'err', str(e)

            # Raise exception if mask was needed and could not find any
            if mask_files == {}:
                raise Exception('Could not find mask files ({})'.format(self.mask_pattern))

        return mask_files

    """
    General loop per file
    """
    def check_spatial_completeness(self):
       
        # Progress init
        i = 0
        n = len(self.files) # read/calc_stats

        # Gather statistics per file
        mv = 0
        uv = 0
        errors_mv = ''
        errors_uv = ''

        # Read mask (if any)
        mask_files = self.read_masks()

        # Loop over files (grib and netcdf follow different strategies)
        for f in self.files:
            # Progress update               
            i += 1
            print_progress(i, n)

            # Get number of missing values
            if f.endswith('.grib'):
                # ECCODES / GRIB
                gc = GribFileCheck(f)
                mvd, uvd = gc.get_grib_mv(mask_files)
            else:
                # XARRAY / NETCDF
                mvd, uvd, msg = self.missing_values_xarray(f, mask_files)

            # Error occurred exit
            if mvd == -1:
                self.logger.error(msg)
                return 'err', msg

            # Collect stats/errors
            if mvd != 0:                                              
                errors_mv = errors_mv + '{} ({} mv)'.format(os.path.basename(f), mvd) + ', '
            if uvd != 0:
                errors_uv = errors_uv + '{} ({} uv)'.format(os.path.basename(f), uvd) + ', '
            
            # Update general counters
            mv += mvd
            uv += uvd

        # Dump errors
        if errors_mv != '':
            self.logger.error('Files with missing values (NaN where val should be) - [mv]:\n')
            self.logger.error(' ' + errors_mv)
        if errors_uv != '':
            self.logger.error('Files with unnecessary values (val where NaN should be) - [uv]:\n')
            self.logger.error(' ' + errors_uv)

        # Final message
        if mv == 0 and uv == 0:            
            msg = 'Files do not contain missing values'
            if self.land_sea_mask:
                msg += ' and match the land/sea mask'      
            return 'ok', msg
        else:            
            msg = 'Files contain missing values. Check log messages in the following pages'
            return 'err', msg

    """
    Main function
    """
    def main(self):
       
        # Do the actual work
        res, msg = self.check_spatial_completeness()

        if res == 'ok':
            self.logger.info(msg)
        else:
            self.logger.error(msg)

        # Prepare output
        return { 
            'res': res, 
            'msg': msg
        }
    
if __name__ == '__main__':
    files = [ '/data/dqc_test_data/seasonal/seasonal-monthly-pressure-levels/geopotential/ukmo-14-20160901.grib' ]
    varname = 'z'
    dt = [ 'em', 'fcmean', 'hcmean' ]
    system = ''
    origin = ''
    cds_dataset = 'reanalysis-era5-single-levels'
    masks_dir = '/shared/cds_downloads/masks'
    lsm = 'no'
    t = SpatialCompletenessTest(files, varname, dt, cds_dataset, system, origin, masks_dir, lsm)
    print(t.check_spatial_completeness())
    sys.exit()

