import xarray as xr
from PIL import Image, ImageDraw, ImageFont
import os
import moviepy.video.io.ImageSequenceClip

def calculategetValuesColormap(nc2,year):#*
    """ Calculate values of colormap

    Args:
        nc (nc data): all layer of nc
        year (int): year

    Returns:
        Min (float): Minimum value
        Max (float): Maximun value
        q1 (float): q1 value
        q50 (float): q50 value
        q25 (float): q25 value
        q75 (float): q75 value
        q99 (float): q99 value
    """
    import numpy as np
    try:
        q1=np.around(np.nanquantile(nc2[int(year)-1987,:,:].values, 0.01),2)
        Min=np.around(np.nanmin(nc2[int(year)-1987,:,:].values),2)
        Max=np.around(np.nanmax(nc2[int(year)-1987,:,:].values),2)
        q99=np.around(np.nanquantile(nc2[int(year)-1987,:,:].values, 0.99),2)
        q50= np.around((q1+q99)/2,2)#np.around(np.nanquantile(nc.DHW[int(year)-1987,:,:].values, 0.50),1)
        q25= np.around((q1+q50)/2,2)#np.around(np.nanquantile(nc.DHW[int(year)-1987,:,:].values, 0.25),1)
        q75= np.around((q50+q99)/2,2)#np.around(np.nanquantile(nc.DHW[int(year)-1987,:,:].values, 0.75),1)
        if q99<10:
            q99=8
            q1=0
            q25=2
            q50=4
            q75=6
    except Exception:
        pass
    return Min,Max,q1,q50,q25,q75,q99

def textdraw(back_im,text,x,y,color,size=18,colormap=False):
    draw = ImageDraw.Draw(back_im)
    title_font = ImageFont.truetype('Roboto/Roboto-Regular.ttf', size)
    textwidth, textheight = draw.textsize(str(text))
    #print(textwidth, textheight,text)
    if colormap:
        x=x-textheight
    draw.text((x, y), str(text),color,title_font)
    return back_im

def ProcessAllImage(ssp,model,Colormap):
    cc=0
    Var="DHW"
    for i in ssp:
        for j in model:
            ListY=[]
            for year in range(1987,2101):
                ListY.append('/home/mario/Documentos/Ocean/NetcdfToPng/SinCoral/%s_%s_%s_%s_DHW_%s.png'%(Colormap,Var,i,j,year))
            movie_clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(ListY, 2)
            movie_clip.write_videofile("Videos/Animated_%s_%s_%s_%s_OFF"%(Colormap,Var,i,j)+".webm")

                #except:
                #   print(3432)
                #break
            #break
        #break
    

ssp=("ssp245","ssp370","ssp585")
model=("BCC-CSM2-MR","CESM2","CanESM5","EC-Earth3","IPSL-CM6A-LR","MIROC6","MRI-ESM2-0","NorESM2-MM")
Colormaps=['Spectral','ocean',"coolwarm","RdYlBu"]
for Colormap in Colormaps:
    ProcessAllImage(ssp,model,Colormap)
