#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug  5 11:58:56 2022

@author: bertelsl
"""
import os
import glob
import netCDF4
import json
import xarray as xr
import numpy as np
import pandas as pd

CROPTYPES_LUCAS = ['Barley',
                                    'Common wheat',
                                    'Cotton',
                                    'Dry pulses',
                                    'Durum wheat',                                   
                                    'Grassland without tree/shrub cover',
                                    'Maize',
                                    'Oats',
                                    'Olive groves',
                                    'Other fibre and oleaginous crops',
                                    'Other fresh vegetables',
                                    'Potatoes',
                                    'Rape and turnip rape',
                                    'Rice',
                                    'Rye',
                                    'Soya',
                                    'Sugar beet',
                                    'Sunflower',
                                    'Tomatoes',
                                    'Triticale',
                                    'Vineyards']

#================================================================================================================
class cGroupLUCAS(object):
#================================================================================================================
    def __init__(self, Info):        
#================================================================================================================
        
        self.fIndir = Info['fIndir']
        self.fOutdir = Info['fOutdir']
        self.periods = Info['periods']
        self.newT = pd.date_range("2017-09-01", periods=Info['periods'])
 
#================================================================================================================
    def start_processing(self):        
#================================================================================================================
        
        aInfiles = glob.glob(os.path.join(self.fIndir, '*.nc'))

        for croptype in CROPTYPES_LUCAS:
            
            print(' * Processing for {}'.format(croptype))
      
            CT = croptype.replace('/', '-')
            CT = '_'.join(CT.split(' '))
                        
            fOut = os.path.join(self.fOutdir, '{}.nc'.format(CT))


            if os.path.isfile(fOut):
                continue

            data_found = False

            for fInfile in aInfiles:
                
                print('\r   - {}'.format(os.path.basename(fInfile)), end='')
            
                data = xr.load_dataset(fInfile)
                
                aCroptypes = data['labels'].values
                
                if croptype not in aCroptypes:
                    continue
                
                subset = None
                subset = data.sel(labels=croptype)
                
                if not data_found:
                    data_found = True
                    
                    if len(np.shape(subset['B02'].values)) == 1:
                        aB02 = np.reshape(subset['B02'].values, (1, self.periods))
                        aB03 = np.reshape(subset['B03'].values, (1, self.periods))
                        aB04 = np.reshape(subset['B04'].values, (1, self.periods))
                        aB05 = np.reshape(subset['B05'].values, (1, self.periods))
                        aB06 = np.reshape(subset['B06'].values, (1, self.periods))
                        aB07 = np.reshape(subset['B07'].values, (1, self.periods))
                        aB08 = np.reshape(subset['B08'].values, (1, self.periods))
                        aB8A = np.reshape(subset['B8A'].values, (1, self.periods))
                        aB11 = np.reshape(subset['B11'].values, (1, self.periods))
                        aB12 = np.reshape(subset['B12'].values, (1, self.periods))
                        aVH = np.reshape(subset['VH'].values, (1, self.periods))
                        aVV = np.reshape(subset['VV'].values, (1, self.periods))
                    else:
                        aB02 = subset['B02'].values
                        aB03 = subset['B03'].values
                        aB04 = subset['B04'].values
                        aB05 = subset['B05'].values
                        aB06 = subset['B06'].values
                        aB07 = subset['B07'].values
                        aB08 = subset['B08'].values
                        aB8A = subset['B8A'].values
                        aB11 = subset['B11'].values
                        aB12 = subset['B12'].values
                        aVH = subset['VH'].values
                        aVV = subset['VV'].values
                    
                    aLat = subset['lat'].values
                    aLon = subset['lon'].values
                else:
                    aLat = np.append(aLat, [subset['lat'].values])
                    aLon =np.append( aLon, [subset['lat'].values])
                        
                    if len(np.shape(subset['B02'].values)) == 1:
                        aB02 = np.concatenate((aB02, np.reshape(subset['B02'].values, (1, self.periods))), axis = 0)
                        aB03 = np.concatenate((aB03, np.reshape(subset['B03'].values, (1, self.periods))), axis = 0)
                        aB04 = np.concatenate((aB04, np.reshape(subset['B04'].values, (1, self.periods))), axis = 0)
                        aB05 = np.concatenate((aB05, np.reshape(subset['B05'].values, (1, self.periods))), axis = 0)
                        aB06 = np.concatenate((aB06, np.reshape(subset['B06'].values, (1, self.periods))), axis = 0)
                        aB07 = np.concatenate((aB07, np.reshape(subset['B07'].values, (1, self.periods))), axis = 0)
                        aB08 = np.concatenate((aB08, np.reshape(subset['B08'].values, (1, self.periods))), axis = 0)
                        aB8A = np.concatenate((aB8A, np.reshape(subset['B8A'].values, (1, self.periods))), axis = 0)
                        aB11 = np.concatenate((aB11, np.reshape(subset['B11'].values, (1, self.periods))), axis = 0)
                        aB12 = np.concatenate((aB12, np.reshape(subset['B12'].values, (1, self.periods))), axis = 0)
                        aVH = np.concatenate((aVH, np.reshape(subset['VH'].values, (1, self.periods))), axis = 0)
                        aVV = np.concatenate((aVV, np.reshape(subset['VV'].values, (1, self.periods))), axis = 0)
                    else:
                        aB02 = np.concatenate((aB02, subset['B02'].values), axis = 0)
                        aB03 = np.concatenate((aB03, subset['B03'].values), axis = 0)
                        aB04 = np.concatenate((aB04, subset['B04'].values), axis = 0)
                        aB05 = np.concatenate((aB05, subset['B05'].values), axis = 0)
                        aB06 = np.concatenate((aB06, subset['B06'].values), axis = 0)
                        aB07 = np.concatenate((aB07, subset['B07'].values), axis = 0)
                        aB08 = np.concatenate((aB08, subset['B08'].values), axis = 0)
                        aB8A = np.concatenate((aB8A, subset['B8A'].values), axis = 0)
                        aB11 = np.concatenate((aB11, subset['B11'].values), axis = 0)
                        aB12 = np.concatenate((aB12, subset['B12'].values), axis = 0)
                        aVH = np.concatenate((aVH, subset['VH'].values), axis = 0)
                        aVV = np.concatenate((aVV, subset['VV'].values), axis = 0)
            
            print('')
                   
            if not data_found:
                continue
            
            new_data = xr.Dataset(
                data_vars=dict(
                    B02=(["feature", "date"], aB02),
                    B03=(["feature", "date"], aB03),
                    B04=(["feature", "date"], aB04),
                    B05=(["feature", "date"], aB05),
                    B06=(["feature", "date"], aB06),
                    B07=(["feature", "date"], aB07),
                    B08=(["feature", "date"], aB08),
                    B8A=(["feature", "date"], aB8A),
                    B11=(["feature", "date"], aB11),
                    B12=(["feature", "date"], aB12),
                    VH=(["feature", "date"], aVH),
                    VV=(["feature", "date"], aVV),
                ),
                coords=dict(
                    date=(self.newT),
                    lat=(["feature"], aLat),
                    lon=(["feature"], aLon),
                ),
                attrs=dict(description="JFdist applied on full date range data."),
            )

            new_data.to_netcdf(fOut)
            
#================================================================================================================
if __name__ == '__main__':
#================================================================================================================

    Info = {
        'fIndir': r'/data/EEA_HRL_VLCC/user/luc/data/LUCAS2018/1_HANTS_preprocessed_allbands/',
        'fOutdir': r'/data/EEA_HRL_VLCC/user/luc/data/LUCAS2018/2_HANTS_crops/',
        'periods': 577 # 2017/09/01 till 2019/03/31
        }

    oGroupLUCAS = cGroupLUCAS(Info)
    oGroupLUCAS.start_processing()





