#!/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 os
import subprocess
from datetime import date
from datetime import datetime
from cdo import Cdo
import numpy as np

cdo = Cdo()

# check leadtimes or frequency of the variable
# This will be checked using CDO

class temporal_consistency_test:

    def __init__(self,path,time_interval):
        self.type = type
        self.path = path
        print('time_interval')
        print(time_interval)
        self.units = time_interval[0][0]
        self.interval = time_interval[1:][0]
        print(interval)
        print('interval')
        print(units)
        print('units')
        self.files = self.dir_or_file()
        try: 
            print("Checking file")
            files = self.files
        except: 
            print("Checking dir")
            files = self.list_files_folder()
        self.check(files)
    def diff_dates(date1, date2,units,delta):
       print(abs(date2.month-date1.month))
       if (units == month):
           if abs(date2.month-date1.month) != delta :
               print('error')
           else:
               print('ok')
       elif (units == hours):
           if abs(date2.month-date1.hour) != delta :
               print('error')
           else:
               print('ok')
       else:
           print("units must be in hours or month")
    dates=cdo.showdate(input='/data/cds_archives/seasonal/monthly_mean/SLVL/2m_temperature/seasonal_hindcast_ecmwf_system5_monthly_mean_SLVL_2m_temperature_1999_january.grib')
    dates_as_list = [words for segments in dates for words in segments.split()]
    print(dates_as_list[0])
    for d1,d2 in zip(dates_as_list[0::1],dates_as_list[1::1]):
      print(d1,d2)
      print('ok')
      print(d1)
      print(datetime.strptime(d2,'%Y-%m-%d'))
      diff_dates(datetime.strptime(d2,'%Y-%m-%d'),datetime.strptime(d1,'%Y-%m-%d'),units,delta)   
    def dir_or_file(self):
        if os.path.isfile(self.path):
            print("Checking file")
            print(self.path)
            # do the file checking
#            return [self.path]

        elif os.path.isdir(self.path):
            print("Found the following files to check ")
            # list all files in the folder
            list_files = self.list_files_folder()
            print(list_files)
            return list_files

    def list_files_folder(self):
        list_files = []
        if os.path.exists(self.path):
            if os.path.isfile(self.path) and self.path.endswith("grib") or self.path.endswith("nc") or self.path.endswith("grb"):
                list_files.append(self.path)
            if os.path.isdir(self.path) or os.path.isfile(self.path):
                for root, dirs, files in os.walk(self.path):
                    print(files)
                    for f in files:
                        if f.endswith("grib") or f.endswith("nc") or f.endswith("grb"):
                            list_files.append(os.path.join(root,f))

                return sorted(list_files)

            else:
                raise Exception('\n\tGiven path is not a valid path\n')

    def check(self):
        print('WILL BE READY SOON')
        print(self.list_files)


if __name__ == "__main__":
    sys.exit()
