#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 20 07:41:12 2022

@author: bertelsl
"""

import os
import glob
import netCDF4
import json
import xarray as xr
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings


iCrop1 = 0
iCrop2 = 7


fIndir = r'/data/EEA_HRL_VLCC/user/luc/data/LUCAS2018/4_HANTS_matrices/'

def hist_intersect(hist1, hist2):
    area = 0.
    
    for iX in range(len(hist1)):
        area += min(hist1[iX], hist2[iX])
        
    return area


afMX_files = glob.glob(os.path.join(fIndir, '*.nc'))
aUnique_CropTypes = []
afMX_files.sort()

for fMX_file in afMX_files:
    crop = os.path.basename(fMX_file).split('_RMSE')[0]  
    aUnique_CropTypes.append(crop.split('.')[0])



fIn1 = afMX_files[iCrop1]
fIn2 = afMX_files[iCrop2]
crop1 = aUnique_CropTypes[iCrop1]
crop2 = aUnique_CropTypes[iCrop2]

xMX1 = xr.load_dataset(fIn1)  
aMX1 = xMX1['MX'].values
aMX1 = aMX1[~np.isnan(aMX1)]

xMX2 = xr.load_dataset(fIn2)  
aMX2 = xMX2['MX'].values
aMX2 = aMX2[~np.isnan(aMX2)]

hist1, bin_edges1 = np.histogram(aMX1, bins=100)
hist2, bin_edges2 = np.histogram(aMX2, bins=100)

hist1_norm = hist1 / len(aMX1)
hist2_norm = hist2 / len(aMX2)


# fig, ax = plt.subplots()
# ax.bar(bin_edges1[:-1], hist1, width=np.diff(bin_edges1), edgecolor="black", align="edge")
# plt.show()

# fig, ax = plt.subplots()
# ax.bar(bin_edges2[:-1], hist2, width=np.diff(bin_edges2), edgecolor="black", align="edge")
# plt.show()

diff = hist_intersect(hist1_norm, hist2_norm)

# x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()

#----
# rects1 = ax.bar(bin_edges1[:-1], hist1_norm, width=np.diff(bin_edges1), label=crop1)
# ax.set_xlim([0, 0.6])
# ax.set_ylim([0, 0.04])
#----

#----
rects1 = ax.bar(bin_edges1[:-1], hist1_norm, width=np.diff(bin_edges1), label=crop1)
rects2 = ax.bar(bin_edges2[:-1], hist2_norm, width=np.diff(bin_edges2), label=crop2, alpha=0.7)
#----

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
# ax.set_title('overlap = {:.2f}'.format(diff))
# ax.set_xticks(x, labels)
ax.legend()


fig.tight_layout()

plt.show()

