#!/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, cz, mask_file, mask_var):
        self.testid = 'test02-spatial_completeness'
        self.logger = logging.getLogger(self.testid)                  
        self.varname = varname
        self.datatype = dt
        self.chunksize = cz
        self.files = files
       
        # Mask (only for ocean and/or land products)
        self.mask_file = mask_file
        self.mask_var = mask_var
        self.mask = (mask_file.strip() != "")

    """
    Loading DATA | Check for missing values
    Returns -1 if data problems, alongisde with an error message
    """
    def missing_values(self, filepath):
        
        # Read data into Xarray
        try:            
            ds = open_dataset(filepath, datatypes=self.datatype, c_chunks=self.chunksize)
            arr = get_variable(ds, self.varname)
        except Exception as e:
            return -1, -1, str(e)

        # Count missing values
        mv = 0
        uv = 0
        
        # Check if there is an ocean mask
        if self.mask:

            # Read mask
            try:
                mask = open_dataset(self.mask_file)            
                mask_arr = get_mask(mask, self.mask_var)
            except Exception as e:
                return -1, -1, str(e)
   
            try:
                mv, uv = find_missing_unnecessary_values(ds, arr, mask_arr, self.varname)

                # Try to avoid memory issues (force delete)
                del mask_arr
                del mask
                del ds
                del arr
            except ValueError:
                raise Exception('The mask provided does not fit the data')

        # No mask, all values should be filled
        else:
            mv, uv = find_missing_unnecessary_values(ds, arr, None, self.varname)

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

    """
    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
        msg = ''

        for f in self.files:
            # Progress update               
            i+=1         
            print_progress(i, n)                        

            # Get number of missing values
            mvd, uvd, msg = self.missing_values(f)        
            if mvd == -1:
                self.logger.error(msg)
                return 'err', msg    
            if mvd != 0:                                              
                self.logger.error('File {} has {} missing values\n'.format(os.path.basename(f), mvd))
            if uvd != 0:                                              
                self.logger.error('File {} has {} unnecessary values\n'.format(os.path.basename(f), uvd))
            
            # Update general counters
            mv+=mvd
            uv+=uvd

        # Final message
        if mv == 0 and uv == 0:            
            msg = 'Files do not contain missing values'
            if self.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__':
    sys.exit()
