'''
#################################################################################
This software prototype has been developed under the Copernicus C3S_512 contract.

Institution: BSC
Author: Jesus Peña-Izquierdo
Email: jesus.pena@bsc.es
#################################################################################
'''

import numpy as np
from pathlib import Path
import os
import yaml
from datetime import date
import logging

import xarray as xr

import matplotlib.pyplot as plt
from pylab import cm
import cartopy.crs as ccrs

from src.tools import tools
t = tools()

from src.scaleformat import scalelabels
ss = scalelabels()

import json
# Dictionary with the JSON content
cdsparamId = json.load(open('cds_datasets.json'))

    
class plotting:
    
    def __init__(self,
                 conf,
                 start_month = 1,
                 level = None
                ):
        
        self.start_month = start_month
        self.level = level
        
        self.dataset_parameters = conf['dataset_parameters']
        
        self.plot_parameters = conf['plot_parameters']
        self.replot = conf['plot_parameters']['replot']
        
        self.variable = conf['dataset_parameters']['variable']
        self.originating_centre =conf['dataset_parameters']['originating_centre']
        self.system = conf['dataset_parameters']['system']
        self.start_months = conf['dataset_parameters']['start_months']
        self.years = conf['dataset_parameters']['years']
        self.leadtime_months = conf['dataset_parameters']['leadtime_months']
        self.leadtime_periods = conf['dataset_parameters']['leadtime_periods']
        self.leadtime_months_T = self.leadtime_months +[self.leadtime_months[-1]+i+1 for i in range(len(self.leadtime_periods))]                
        self.leadtime_dimname = conf['compute_parameters']['xarray_parameters']['leadtime_dimname']
        self.lon_dimname = conf['compute_parameters']['xarray_parameters']['lon_dimname']
        
        self.dataset_sf = conf['dataset_parameters']['dataset_sf']
        self.dataset_ref = conf['dataset_parameters']['dataset_ref']
        self.reference_name = conf['dataset_parameters']['reference_name']

        self.file_format = conf['plot_parameters']['file_format']
        self.figure_size = conf['plot_parameters']['figure_size'] 

        self.projection = conf['plot_parameters']['projection']
        self.colorbar_fraction = conf['plot_parameters']['colorbar_fraction'] 
        self.colorbar_pad =conf['plot_parameters']['colorbar_pad']
        self.figure_dpi = conf['plot_parameters']['figure_dpi']
        self.file_format = conf['plot_parameters']['file_format']
        self.cmap = conf['plot_parameters']['cmap']
        self.nans_color = conf['plot_parameters']['nans_color']
        self.axis_fontsize = conf['plot_parameters']['axis_fontsize']
        self.title_fontsize = conf['plot_parameters']['title_fontsize']
        self.text_fontsize_F = conf['plot_parameters']['text_fontsize_F']
        self.text_fontsize_D = conf['plot_parameters']['text_fontsize_D']
        self.xticks = conf['plot_parameters']['xticks']
        self.yticks = conf['plot_parameters']['yticks']

        self.dimensionless_options = conf['others']['dimensionless_options']
        self.variables_reversed_colormap_in_bias = conf['others']['variables_reversed_colormap_in_bias']
        
        self.paramId = cdsparamId[self.dataset_sf]['variables'][self.variable]['paramId']

        self.figures_path = Path(conf['folders']['figures_path']).joinpath(self.dataset_sf.replace("-","_"), 
                                                                           self.originating_centre \
                                                                           + '_s' \
                                                                           + str(self.system),
                                                                           self.paramId #self.variable,
                                                                          )
        self.metrics_data_path = Path(conf['folders']['metrics_data_path']).joinpath(self.dataset_sf,
                                                                                     self.variable
                                                                                    )
        self.logs_path = Path(conf['folders']['logs_path'])
        self.save_anomaly = conf['folders']['save_figure_copy_in_anomaly_folder']
                
        with open("./src/naming_convention.yaml") as f:
            self.names = yaml.load(f, Loader=yaml.FullLoader)
            
        self.leadtimes_str = ['01','02','03','04','05','06','02-04','04-06']
        
        formatter = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        log_error_file = 'log_error_plot_{}s{}_{}.log'.format(self.originating_centre,
                                                                  self.system,
                                                                  self.variable)
        logging.basicConfig(filename = self.logs_path.joinpath(log_error_file),
                            level = "WARNING",
                            format = formatter,
                            filemode = "w")
            
            

        print('\n#########################')
        print('PLOTTING................')
        print('#########################\n')            
            
        t.print_header(self.dataset_parameters)
    

    def update_level(self):
        
        if 'pressure' in self.dataset_sf:
            self.level_ext2 = '-p' + str(self.level)
            self.level_title = '{}hPa '.format(self.level)
            self.level_ext3 = '-p' + str(self.level)
        else:
            self.level_ext2 = ''
            self.level_ext3 = '-p'
            self.level = None
            self.level_title = ''
        
        
    def plot_map(self,
                 field,
                 print_plot = True,
                 selected_leadtimes = [1]
                ):
        
        # This function plots the all the leadtimes fields within "field".
        
        if isinstance(field, tuple):
            main_field = field[0]
            pval_field = field[1]
            pval = True

        else:
            main_field = field
            pval = False
         
        # Update levels
        self.update_level()
        
        # Load location of plot elements
        with open("./src/plot_element_locations.yaml") as f:
            locs = yaml.load(f, Loader=yaml.FullLoader)
        
        metric_parameters = self.plot_parameters[main_field.name]
        plot_figure = metric_parameters['plot_figure']
        
        if plot_figure:
            
            metric_longname =  metric_parameters['metric_longname']
            metric_shortname = metric_parameters['metric_shortname']
            
            cmap_type = metric_parameters['cmap_type']
            if metric_shortname == 'bias' and self.variable in self.variables_reversed_colormap_in_bias:
                cmap = self.cmap[cmap_type + '_r']
            else:
                cmap = self.cmap[cmap_type]
             
            cbar_nlevels =  metric_parameters['cbar_nlevels']
            if 'cmap_double_white' in metric_parameters:
                cmap_double_white = metric_parameters['cmap_double_white']
                if cmap_double_white == True and (cbar_nlevels % 2) == 0:
                    cbar_nlevels = cbar_nlevels - 1
            else:
                cmap_double_white = False
            cbar_minmax = metric_parameters['cbar_minmax']
            cbar_pminmax = metric_parameters['cbar_pminmax']
            cbar_ndigits = metric_parameters['cbar_ndigits']
            cbar_extend = metric_parameters['cbar_extend'] 

            if metric_shortname == 'bias':
                self.cbar_round = metric_parameters['cbar_round']
            else:
                self.cbar_round = False

            # Recompute cbar_minmax depending of given percentiles cbar_pminmax
            cbar_minmax = t.minmax_percentile(main_field,
                                              cbar_minmax,
                                              cbar_pminmax,
                                              cmap_type = cmap_type,
                                              ndigits = cbar_ndigits
                                             )
            
            units = ''
            if metric_parameters['metric_shortname'] == 'bias':
                if self.units in self.dimensionless_options:
                    units = 'dimensionless'#'[-]'
                else:
                    units = self.units
        
            if print_plot:
                selected_leadtimes = self.leadtime_months_T
                
            
            for leadtime_i in selected_leadtimes:
            
                print('\nPlotting {} for start month {}, leadtime {} and level {}... '.format(metric_longname,
                                                                                    self.start_month,
                                                                                    leadtime_i,
                                                                                              self.level
                                                                                   )
                     )
                
                field_leadtime_i = main_field.sel({self.leadtime_dimname: leadtime_i})

                if leadtime_i <= len(self.leadtime_months):

                    # Single leadtimes
                    month_leadtime_i, _ = t.corresponding_month(start_month = self.start_month,
                                                              ileadtime = leadtime_i - 1
                                                             )
                    name_leadtime_i = self.names['months'][month_leadtime_i]

                elif leadtime_i > len(self.leadtime_months): 

                    # Periods as average of several leadtimes
                    name_leadtime_i = ''
                    for i in self.leadtime_periods[leadtime_i - len(self.leadtime_months) - 1]:
                        month_leadtime_i, _ = t.corresponding_month(start_month = self.start_month,
                                                    ileadtime = i - 1
                                                   )
                        name_leadtime_i = name_leadtime_i + self.names['months'][month_leadtime_i][0]



                month_today = self.names['months'][date.today().month]
                year_today = date.today().year

                leadtime_str = self.leadtimes_str[leadtime_i-1]

                filename = '{}-{}-{}-{}-global{}-{}_{}-s{:02d}-l{}-{}.{}'.format(self.originating_centre,
                                                                               self.system,
                                                                               self.paramId, #self.varname_short,
                                                                               metric_shortname,
                                                                               self.level_ext3,   
                                                                               self.years[0],
                                                                               self.years[1],
                                                                               self.start_month,
                                                                               leadtime_str,
                                                                               self.reference_name.lower(),
                                                                               self.file_format
                                                                              )
                # crpss and rpss are saved with fcrpss and frpss name (and folder) and actual fcrpss and frpss as ffcrpss and ffrpss (it's done like this to have non-fair scores plots in CMS without changing the upload script):
                if '-fcrpss' in filename:
                    filename = filename.replace('fcrpss', 'ffcrpss')
                elif '-frpss' in filename:
                    filename = filename.replace('frpss', 'ffrpss')
                elif '-crpss' in filename:
                    filename = filename.replace('crpss', 'fcrpss')
                elif '-rpss' in filename:
                    filename = filename.replace('rpss', 'frpss')
                
                #special case ukmo_s14 no data for January 1993, so the period is 1994_2016, but the filename needs to be 1993_2016 anyway:
                if 'ukmo-14' in filename and '1994_2016' in filename:
                    filename = filename.replace('1994_2016', '1993_2016')
                

                # Figure filename
                if metric_shortname == 'crpss':
                    metric_path = self.figures_path.joinpath('fcrpss')
                elif metric_shortname == 'rpss':
                    metric_path = self.figures_path.joinpath('frpss')
                elif metric_shortname == 'fcrpss':
                    metric_path = self.figures_path.joinpath('ffcrpss')
                elif metric_shortname == 'frpss':
                    metric_path = self.figures_path.joinpath('ffrpss')
                else:
                    metric_path = self.figures_path.joinpath(metric_shortname)
                filename_path = metric_path.joinpath(filename)   

                # Check if plot already exists. If not or replot is enable, the it plot it
                if os.path.exists(filename_path) and (not self.replot) and print_plot:
                    
                    print('...\n{} found.'.format(filename_path))
                    print('...Plotting skipped.')
                
                else:
                    
                    # Remove to avoid permision problems
                    if os.path.exists(filename_path):
                        os.remove(filename_path)
                    if self.save_anomaly:
                        filename_path_anomaly = Path(str(filename_path).replace('seasonal_monthly_', 'seasonal_postprocessed_'))
                        if os.path.exists(filename_path_anomaly):
                            os.remove(filename_path_anomaly)
                                
                    
                    title = '{}-S{} / {}{}\n{} / {} / {}-{}'.format(self.originating_centre.upper(),
                                                                  self.system,
                                                                     self.level_title,
                                                                  self.varname_long,
                                                                  metric_longname,
                                                                  name_leadtime_i,
                                                                  self.years[0],
                                                                  self.years[1]
                                                                      )

                    footnote = 'Nominal start date: 1st {}\nForecast month: {}\nReference: {}'.format(self.names['months_long'][self.start_month],
                                                                                              leadtime_str,
                                                                                              self.reference_name
                                                                                             )

                    fig = plt.figure(figsize = self.figure_size)


                    if print_plot:
                        plt.ioff()

                    if self.projection == 'robinson':
                        ax = plt.axes(projection = ccrs.Robinson())
                    else:
                        ax = plt.axes(projection = ccrs.PlateCarree())


                    # Colorbar / colormap construction
                    if cmap_double_white:
                        # 2 white intervals around 0
                        cmap = t.generate_white_centred_cmap(nlevels = cbar_nlevels-1, original_cmap = cmap)
                    else:
                        # 1 white interval centred in 0
                        cmap = cm.get_cmap(cmap, cbar_nlevels-1) 

                    if self.nans_color:
                        cmap.set_bad(color = self.nans_color)
                    
                    if metric_shortname == 'frpss' or metric_shortname == 'fcrpss' or metric_shortname == 'rpss' or metric_shortname == 'crpss':
                        cmap.set_under('lightcyan')
                        test_min_for_cbar_extend = field_leadtime_i.data.flatten()
                        if test_min_for_cbar_extend.min() >= 0 and field_leadtime_i.min().min()>=0:
                            cbar_extend = 'neither'
                        else:
                            cbar_extend = metric_parameters['cbar_extend'] 
                        #if field_leadtime_i.min().min()>=0:
                            #cbar_extend = 'neither'

                    # Resorting the longitude coordinate
                    field_leadtime_i = field_leadtime_i.assign_coords(longitude=(((field_leadtime_i.longitude + 180) % 360) - 180)) \
                                                       .sortby(self.lon_dimname)

                    #p = ax.imshow(field_leadtime_i, interpolation='None', cmap=cmap, transform = ccrs.PlateCarree(), vmin=cbar_minmax[0], vmax=cbar_minmax[1])
                    p = field_leadtime_i.plot(add_colorbar = False,
                                              transform=ccrs.PlateCarree(),
                                        cmap = cmap,
                                        vmin = cbar_minmax[0],
                                        vmax = cbar_minmax[1],
                                                     ax = ax
                                       )

                    if pval:
                        xlim = ax.get_xlim()
                        ylim = ax.get_ylim()

                        pval_field_leadtime_i = pval_field.sel({self.leadtime_dimname: leadtime_i})
                        
                        # Resorting the longitude coordinate
                        pval_field_leadtime_i = pval_field_leadtime_i.assign_coords(longitude=(((pval_field_leadtime_i.longitude + 180) % 360) - 180)) \
                                                                     .sortby(self.lon_dimname)


                        conf_level = metric_parameters['conf_level']
                         
                        try:
                            #pvalues_hatches = pval_field_leadtime_i.where(pval_field_leadtime_i > conf_level)
                            #ax.contourf(pvalues_hatches.longitude, pvalues_hatches.latitude, pvalues_hatches, transform = ccrs.PlateCarree(), alpha = 0, hatches = ['....'])
                            pval_field_leadtime_i.where(pval_field_leadtime_i > conf_level) \
                                         .plot.contourf(cmap=None,
                                                        hatches=metric_parameters['hatches'], #['////'],
                                                        alpha=0,
                                                        add_colorbar=False,
                                                        ax=ax,
                                                        transform=ccrs.PlateCarree()
                                                       )

                            # To avoid automatic reduction of the domain in case of too many nan's
                            ax.set_xlim(xlim)
                            ax.set_ylim(ylim)
                        
                        except:
                            w1 = "\n-----------WARNING----------\n"
                            w2 = "...Not significant areas (p>conf_level) are too small for hatching.\n"
                            w3 = "...Hatching is avoided\n"
                               
                            print(w1+w2+w3+w1)
                            logging.error(w1+w2+w3+w1)
                            
                
                    #### ROUNDING SCALEBAR LABELS
                    if metric_shortname == 'bias' and self.cbar_round:
                        cbar_ticks = np.linspace(cbar_minmax[0], cbar_minmax[1], cbar_nlevels)
                        cbar_labels_string, scientific_notation_label, cbar_extend = ss.scalelabels(main_field, cbar_nlevels, cbar_extend, cbar_ticks, cbar_minmax)
                                                                         
                    # Colorbar axes 
                    #if metric_shortname == 'bias':
                    #    kwargs = {'format': '%.2f'}
                    #else:
                    #    kwargs = ''
                    cbar = plt.colorbar(p, fraction = self.colorbar_fraction,
                                        pad = self.colorbar_pad,
                                        extend = cbar_extend,
                                        ticks = np.linspace(cbar_minmax[0],
                                                            cbar_minmax[1],
                                                            cbar_nlevels
                                                           ),
                                        #**kwargs #if used then cbar.ax.ticklabel_format below doesn't work (also it doesn't work with "text labels")
                                       )
                    if metric_shortname == 'bias' and self.cbar_round:
                        # Setting labels in text format
                        cbar.set_ticklabels(cbar_labels_string)
                    else:
                        # Setting colorbar axis format. Scientific notation beyond 10**+-m
                        cbar.ax.ticklabel_format(axis='y', style='sci', scilimits=(-2, 2))

                    # Setting colorbar axis font size
                    cbar.ax.tick_params(labelsize = self.axis_fontsize)
                                       

                    # Adding coastline
                    ax.coastlines()

                    if self.projection != 'robinson':
                        xticks = np.arange(self.xticks[0], self.xticks[1]+1, self.xticks[2])
                        ax.set_xticks(xticks)
                        xticks_W = ['{:.0f}W'.format(np.abs(x)) for x in xticks if x<0]
                        xticks_E = ['{:.0f}E'.format(np.abs(x)) for x in xticks if x>0]
                        xticks_EW = xticks_W + ['0'] + xticks_E
                        ax.set_xticklabels(xticks_EW)
    
                        yticks = np.arange(self.yticks[0], self.yticks[1]+1, self.yticks[2])
                        ax.set_yticks(yticks)
                        yticks_S = ['{:.0f}S'.format(np.abs(y)) for y in yticks if y<0]
                        yticks_N = ['{:.0f}N'.format(np.abs(y)) for y in yticks if y>0]
                        yticks_SN = yticks_S + ['0'] + yticks_N
                        ax.set_yticklabels(yticks_SN)
    
                        ax.tick_params(labelsize = self.axis_fontsize) 
    
                    # Removing axis labels
                    plt.xlabel('')
                    plt.ylabel('')
    
    
                    if metric_shortname == 'bias' and self.cbar_round:
                        #add scientific notation label on top of the scalebar:
                        plt.text(x = locs['plot_map']['x_units'], y = 1.06, 
                             s = scientific_notation_label,
                              transform=ax.transAxes,
                              #fontname='Arial',
                              #fontweight='bold',
                              horizontalalignment = 'center',
                            fontsize = self.text_fontsize_F - 2 - 2 #(2 smaller than the units)                 
                        ) 
    
                    # Adding title
                    plt.title(title, 
                              fontsize = self.title_fontsize,
                              multialignment='center',
                              #fontname='Arial', 
                              fontweight='bold',
                              pad = locs['plot_map']['pad']
                             )
    
                    # Adding units
                    plt.text(x = locs['plot_map']['x_units'], y = locs['plot_map']['y_units'] ,
                             s = units,
                             transform=ax.transAxes,
                             #fontname='Arial',
                             #fontweight='bold',
                             horizontalalignment = 'center',
                             fontsize = self.text_fontsize_F                 
                            )
         
                    if footnote:
                        # Adding footnote1
                        plt.text(x = locs['plot_map']['x_footnote'], y = locs['plot_map']['y_footnote'], 
                                 s = footnote,
                                 transform=ax.transAxes,
                                 verticalalignment = 'top',
                                 horizontalalignment = 'left',
                                 #fontname = 'Arial',
                                 fontsize = self.text_fontsize_F
                                )


                    if self.originating_centre == 'ecmwf' and (self.variable != 'runoff' or (self.variable == 'runoff' and (metric_shortname == 'bias' or metric_shortname == 'corr'))): # to solve issue of dotted line
                        my_file_fig = Path(self.logs_path).joinpath(self.variable + '-fig_tmp.png') 
                        my_file_logo = Path(self.logs_path).joinpath(self.variable + '-figlogo_tmp.png')
                        
                        plt.savefig(my_file_fig,
                                        dpi = self.figure_dpi,
                                        format = self.file_format,
                                        bbox_inches='tight')
                        
                        plt.close(fig)
                        fig = plt.figure(figsize = self.figure_size)
                        if print_plot:
                            plt.ioff()
                        if self.projection == 'robinson':
                            ax = plt.axes(projection = ccrs.Robinson())
                        else:
                            ax = plt.axes(projection = ccrs.PlateCarree())
                    
                    # Adding C3S logo
                    plt.text(x = locs['plot_map']['x_logo'], y = locs['plot_map']['y_logodate'], #+0.02 is to solve issue of dotted line that sometimes appears in the plot when adding the logo or generation date
                             s = 'Copernicus Climate Change Service',
                             transform=ax.transAxes,
                             verticalalignment = 'bottom',
                             horizontalalignment = 'left', #'right',
                             #fontname = 'Arial',
                             fontsize = self.text_fontsize_D
                            )
                    # Adding generation date
                    plt.text(x = locs['plot_map']['x_date']-0.02, y = locs['plot_map']['y_logodate'], #+0.02 is to solve issue of dotted line that sometimes appears in the plot when adding the logo or generation date
                             s = 'Generated: {} {}'.format(month_today, year_today),
                             transform=ax.transAxes,
                             verticalalignment = 'bottom',
                             horizontalalignment = 'right',
                             #fontname = 'Arial',
                             fontsize = self.text_fontsize_D
                            )

                    if self.originating_centre == 'ecmwf' and (self.variable != 'runoff' or (self.variable == 'runoff' and (metric_shortname == 'bias' or metric_shortname == 'corr'))): # to solve issue of dotted line
                        plt.savefig(my_file_logo,
                                        dpi = self.figure_dpi,
                                        format = self.file_format,
                                        bbox_inches='tight')
                        plt.close(fig)
                  
                        command = "convert " + str(my_file_logo) + " -gravity North -chop 0x1650 " + str(my_file_logo)
                        os.system(command)
                        
                        command = "montage " + str(my_file_fig) + ' ' + str(my_file_logo) + " -tile 1x2 -geometry +0+0 " + str(my_file_fig)
                        os.system(command)
                  
                        command = 'rm ' + str(my_file_logo)
                        os.system(command)
                        

                    # Printing the figure
                    if print_plot:

                        if not os.path.exists(metric_path):
                            os.makedirs(metric_path)

                        if self.originating_centre == 'ecmwf' and (self.variable != 'runoff' or (self.variable == 'runoff' and (metric_shortname == 'bias' or metric_shortname == 'corr'))): # to solve issue of dotted line
                            command = 'cp ' + str(my_file_fig) + ' ' + str(filename_path)
                            os.system(command)

                            command = 'rm ' + str(my_file_fig)
                            os.system(command)
                            
                        else:
                            plt.savefig(filename_path,
                                        dpi = self.figure_dpi,
                                        format = self.file_format,
                                        bbox_inches='tight')
                            
                        if self.save_anomaly:
                            metric_path_anomaly = Path(str(metric_path).replace('seasonal_monthly_', 'seasonal_postprocessed_'))
                            if not os.path.exists(metric_path_anomaly):
                                os.makedirs(metric_path_anomaly)

                            if self.originating_centre == 'ecmwf' and (self.variable != 'runoff' or (self.variable == 'runoff' and (metric_shortname == 'bias' or metric_shortname == 'corr'))): # to solve issue of dotted line
                                command = 'cp ' + str(filename_path) + ' ' + str(filename_path_anomaly)
                                os.system(command)
                            else:
                                plt.savefig(filename_path_anomaly,
                                        dpi = self.figure_dpi,
                                        format = self.file_format,
                                        bbox_inches='tight')
                        
                        if self.originating_centre == 'ecmwf' and (self.variable != 'runoff' or (self.variable == 'runoff' and (metric_shortname == 'bias' or metric_shortname == 'corr'))): # to solve issue of dotted line
                            print('...{} printed.'.format(filename_path))
                            if self.save_anomaly:
                                print('...{} printed.'.format(filename_path_anomaly))
                        else:
                            plt.close(fig)
                            print('...{} printed.'.format(filename_path))
                            if self.save_anomaly:
                                print('...{} printed.'.format(filename_path_anomaly))

                        
                        
                        
                            

                
                
                
    def load_metrics(self):
        
        # This function loads previously computed metrics. To be used for debugging plotting scripts.
        # It also add required variable attributes
        
        # Update levels
        self.update_level()
        print(self.level_ext2)
            
        # File to be loaded.
        filename = 'EQCmetrics-{}s{}-{}-{}to{}-s{:02d}{}.nc'.format(self.originating_centre,
                                                              self.system,
                                                              self.variable,
                                                              self.years[0],
                                                              self.years[1],
                                                              self.start_month,
                                                                self.level_ext2
                                                             )
        
        filename_path = self.metrics_data_path.joinpath(filename)
        
        if os.path.exists(filename_path):
            ok_load = True

            print('\nLoading previously computed metrics from...\n{}'.format(filename_path))

            data = xr.open_dataset(filename_path)

            # Extracting required attributes (longname, shortname and units)
            attrs = t.extract_attrs(data,
                                    attrs_in = ['units', 'varname_short', 'varname_long']
                                   )

            self.units = attrs['units']
            self.varname_short = attrs['varname_short']
            self.varname_long = attrs['varname_long']

            print('\nFile {} loaded.'.format(filename_path))
            
        else:
            ok_load = False
            data = None
            
            e0 = '---------------------------------------------------\n'
            e1 = '-----------------------ERROR-----------------------\n'
            e2 = 'Metrics files missing: {}\n'.format(filename_path)
            e3 = '\Plotting for {}s{}-{}:\n...level: {}\n...start_month: {}\n...SKIPPED!!!\n'.format(self.originating_centre,
                                                                                       self.system,
                                                                                       self.variable,
                                                                                                     self.level,
                                                                                       self.start_month
                                                                                      )
            print(e0+e1+e2+e3+e0)

        return data, ok_load
