import xarray as xr
from PIL import Image, ImageDraw, ImageFont
import os
import moviepy.video.io.ImageSequenceClip
Var="DHW"
ssp=("ssp245","ssp370","ssp585")
model=("BCC-CSM2-MR","CESM2","CanESM5","IPSL-CM6A-LR","MIROC6","NorESM2-MM","MRI-ESM2-0","EC-Earth3","ensemble5","ensemble8")
Colormaps=['noaa']
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)-1986,:,:].values, 0.01),2)
        Min=np.around(np.nanmin(nc2[int(year)-1986,:,:].values),2)
        Max=np.around(np.nanmax(nc2[int(year)-1986,:,:].values),2)
        q99=np.around(np.nanquantile(nc2[int(year)-1986,:,:].values, 0.99),1)
        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)
    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
    for i in ssp:
        for j in model:
            ff="../Data/%s_%s_%s_DHW.nc"%(Var,i,j)
            print(ff)
            nc = xr.open_dataset(ff, decode_coords="all")
            for countyear in range(len(nc.time)):


                #try:
                year=int(nc.time[countyear].values)
                path='./SinCoralN/%s_%s_%s_%s_DHW_%s.png'%(Colormap,Var,i,j,year)
                isFile = os.path.isfile(path)
                if isFile:
                    print(" Ya existe "+ path)
                    continue
                #print(ff,year)
                im1 = Image.open('./CapasJuntas_%s.png'%(Colormap))
                im2 = Image.open('../2nc2image/img/%s_%s_%s_%s_DHW_%s.png'%(Colormap,Var,i,j,year))
                
                back_im = im1.copy()
                back_im.paste(im2, (0, 27))
                #final2 = Image.new("RGBA", back_im.size)
                #final2 = Image.alpha_composite(final2, back_im)
                #im3 = Image.open("/home/mario/Documentos/Ocean/NetcdfToPng/CapasCoralJunta.png")
                #final2 = Image.alpha_composite(final2, im3)
                #back_im=final2
                im3 = Image.open("./FondoRosa.png")
                final2 = Image.alpha_composite(im3,back_im)
                back_im=final2
                x=10
                y=0
                back_im=textdraw(back_im,year,x,y+2,(0, 0, 0))
                #back_im.save('rocket_pillow_paste_pos.png', quality=95)
                x=500
                y=0
                back_im=textdraw(back_im,i,x,y+2,(0, 0, 0))
                x=570
                y=0
                back_im=textdraw(back_im,j,x,y+2,(0, 0, 0))
                #back_im.save('rocket_pillow_paste_pos.png', quality=95)
              
                back_im.save('./SinCoralN/%s_%s_%s_%s_DHW_%s.png'%(Colormap,Var,i,j,year), quality=100)

            ListY=[]
            path="Videos/Animated_%s_%s_%s_%s_OFF"%(Colormap,Var,i,j)+".webm"
            isFile = os.path.isfile(path)
            if isFile:
                print(" Ya existe "+ path)
                continue
            for year in range(1986,2101):
                ListY.append('./SinCoralN/%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
for Colormap in Colormaps:
    ProcessAllImage(ssp,model,Colormap)

for Colormap in Colormaps:
    for i in ssp:
        for j in model:
            ListY=[]
            for year in range(1986,2101):
                ListY.append('ConCoralN/%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_ON"%(Colormap,Var,i,j)+".webm")

