#!/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)
#       Ivan Jose Cernicharo Ortiz (ivan.cernicharo@bsc.es)

import sys
import logging
import os
import subprocess
from cdo import *

# Local import
from utils.utils_files import *

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

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

    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
                        
            for inf in info:
                if 'gridtype' in inf:
                    gt = inf.split('=')[1].strip()
                if 'xinc' in inf:
                    gr = inf.split('=')[1].strip()

            if gt != self.grid_type or gr != self.grid_int:
                res = False
                self.logger.error('Spatial inconsistency found [{} {}] vs [{} {}]'.format(
                    self.grid_type, self.grid_int, gt, gr))
                
        # Final message
        if res:
            msg = 'Files are spatially consistent'
            self.logger.info(msg)            
            return 'ok', msg
        else:
            msg = 'Spatial inconsistencies found. Check log for details'
            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
        }        

