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

from cdo import *

# Local import
from dqc_wrapper.utils.utils_files import *

"""
Class: Spatial consistency checks
---
- Uses CDO python bindings
- Checks grid type and resolution
"""
class SpatialConsistencyTest:

    def __init__(self, files, gridtype, gridinterval, gridmap, dual):
        self.testid = 'test04-spatial_consistency'
        self.logger = logging.getLogger(self.testid)
        self.grid_type = gridtype
        self.grid_mapping_name = gridmap
        self.files = files

        # Some products have two resolutions (one doubles the other)
        self.grid_int = [ float(gridinterval) ]
        if dual == 'yes':
            self.grid_int = [ float(gridinterval), float(gridinterval)*2.0 ]

    def check_spatial(self):
        # For all files
        cdo = Cdo()
        res = True

        # Progress init
        i = 0
        n = len(self.files)
        print()

        for f in self.files:
            # Progress update
            i += 1
            print_progress(i, n)
            try:
                info = cdo.griddes(input=f)
            except:
                self.logger.error('Bad file format (cdo cannot read file)')
                print(
                    'ERROR: Bad file format ({})'.format(os.path.basename(f)))
                res = False
                break

            gt, gr = None, None
            gm = ''
            for inf in info:
                if 'gridtype' in inf:
                    gt = inf.split('=')[1].strip()
                if 'xinc' in inf:
                    gr = float(inf.split('=')[1].strip())
                if 'grid_mapping_name' in inf:
                    gm = inf.split('=')[1].strip()

            # Check projection only if lambert/UERRA
            if gm != '':
                if gt != self.grid_type or not(gr in self.grid_int) or gm != self.grid_mapping_name:
                    res = False
                    self.logger.error('Found [{} {} {}] should be [{} {} {}]'.format(
                        gt, gr, gm, self.grid_type, self.grid_int, self.grid_mapping_name))
            else:
                if gt != self.grid_type or not(gr in self.grid_int):
                    res = False
                    self.logger.error('Found [{} {}] should be [{} {}]'.format(
                        gt, gr, self.grid_type, self.grid_int))
                
        # Final message
        if res:
            msg = 'Files are spatially consistent (grid_type={}, grid_interval={})'.format(self.grid_type, self.grid_int)
            self.logger.info(msg)            
            return 'ok', msg
        else:
            msg = 'Spatial inconsistencies found. Check log messages in the following pages'
            self.logger.error(msg)            
            return 'err', msg

    def main(self):

        # Do the actual work
        res, msg = self.check_spatial()

        # Prepare output
        return { 
            'res': res,  
            'msg': msg
        }        

