#!/usr/bin/env python


import os
import sys
import getpass  # just to get user login
import shutil
import datetime
import glob
import json

 
#===============================================================================
#@   Choices
#===============================================================================

debug=False

img_pattern_file='img_pattern.py'      # default

#-------------------------------------------------------------------------------
#   Choix de l'atlas
#-------------------------------------------------------------------------------
###   01_data_processing

var1='no3'    #   thetao so uo vo wo wmo hfdsO o2 no3 tauuo tauvo
subdir="01_data_processing"
title1='Data Processing '+var1
img_test_exists='01_extract_K=1'


###   03_PERU_isodepth
#var1='wod'    #   thetao so wo wod hfdsO o2 no3 tau
#subdir="03_PERU_isodepth"
#title1='PERU '+var1+' atlas'

#if var1 == 'hfdsO' :
#   img_test_exists='PERU_hfdsO_pcf025'
#elif var1 == 'tau' : 
#   img_test_exists='PERU_tau_pcf025'
#   img_pattern_file='img_pattern_tau.py'
#else :
#   img_test_exists='PERU_'+var1+'_sst_pcf025'


###   04_isopycnes
#var1='vo'    #   so o2 no3 vo    ### Variable qui sert à faire la liste des exp disponibles
#subdir="04_isopycnes"
#title1='PACIFIC isopycnes ['+var1+' dispo]'
#img_test_exists='isopycne_'+var1+'_pcf025'

#-------------------------------------------------------------------------------

num_col=3   #   nombre de colonnes pour répéter le nom de l'expérience

num_header=2   #   nombre de lignes pour répéter les headers

F_from_exp_list=False
exp_list_name='cmip6_HR'

Klev1="20-26";  lev1='69m-133m'
Klev2="24";     lev2="97m"
Klev3="18";     lev3="47m"

img_root_dir='./../images/'
html_filename='atlas'

if F_from_exp_list :
   title1 = title1 + '     (exp_list : '+ exp_list_name+')'
else :
   title1 = title1 + '     (all exp)'

###   Obs
if (var1 == 'uo') | (var1 == 'vo') : 
   obs='glorys12v1'   #  thetao, so, uo, vo
elif (var1 == 'thetao') | (var1 == 'so') | (var1 == 'o2') | (var1 == 'no3'): 
   obs='woa23'        #  thetao, so, o2, no3
else :
   obs='none'

###   list_exp_id_dxdyxdz
with open('./list_exp_id_dxdydz_80W_10S.json.REF_2026_04_01') as f01:
   list_exp_id_dxdydz=json.load(f01); f01.close()

   
#===============================================================================
#@   Definitions
#===============================================================================
local_time1=datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')    #  '2018-09-19'
local_time3=datetime.datetime.strftime(datetime.datetime.now(), 'the %d %b %Y at %H:%M:%S')    #  '20-Jun-2019 at 16:27:43'
local_time4=datetime.datetime.strftime(datetime.datetime.now(), '%Y_%m_%d-%H_%M_%S')    #  '2019_08_12-18_33_13'

script_name=os.path.basename(sys.argv[0])

script_name_root=script_name.split('_3D')[0]

script_dir=os.getcwd()+'/'



#===============================================================================
#@   Main
#===============================================================================

html_filename=html_filename+'.'+var1

if F_from_exp_list :
   ###   read selected_list :
   with open('exp_list-'+exp_list_name+'.py') as f0: exec(f0.read())
   html_filename=html_filename+'.list_'+exp_list_name
else : 
   html_filename=html_filename+'.all_exp'


###   to open/create a new html file in the write mode
#f1 = open(script_name_root+'_'+var1+'.html', 'w')
f1 = open('./'+subdir+'/'+html_filename+'.html', 'w')
  

#-------------------------------------------------------------------------------
#@@     HTML & javascript header    - begin - 
#-------------------------------------------------------------------------------
html_template_begin1 = """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">

  <head>
"""
f1.write(html_template_begin1)

f1.write('   <title>'+title1+'</title>\n')

html_template_begin2 = """
    <link type="text/css" rel="stylesheet" href="./css/chris_EUC_Upwelling.css" title="feuille de style EUC_Upwelling" />

  <meta charset="UTF-8" /></head>



<!--========================================================================-->
<!--                      Javascript (Open Windows)                         -->
<!--========================================================================-->
  <script type="text/javascript">
    // initialise the visibility check
    function affCache(idDiv) {
    var div = document.getElementById(idDiv);
    if (div.style.display == "none")
    div.style.display = "";
    else
    div.style.display = "none";
    }

    // Chargement images dans window.open
    function ChargeImage1(img1) {
    window.open(img1,img1,'width=1000, height=700, status=no').focus();return false;
    }
  </script>


<!--========================================================================-->
<!--                              BODY                                      -->
<!--========================================================================-->
  <body>
"""
f1.write(html_template_begin2)

f1.write('    <h1>'+title1+'</h1>\n')


html_template_begin3 = """
<!--========================================================================-->
<!--                              TABLE                                     -->
<!--========================================================================-->
<table border="1px">
  <tbody>
"""
f1.write(html_template_begin3)
#-------------------------------------------------------------------------------
#@@     HTML & javascript header    - end - 
#-------------------------------------------------------------------------------


### CHRIS PARAMETRE list 
#    soit list_exp_id_dxdydz
#    soit liste customisée 
#    soit list_HR dans module! 
#
#  if F_from_exp_list :
#     exp_file_list=selected_list
#  else :


ii_cmip5=0
ii_cmip6=0
ii_trop=0

n_cmip5=0
n_cmip6=0
n_trop=0


### =============================================================================
###    contraint de faire un premier passage pour avoir le nombre global de cmip5/6
###    qui sont dispo pour le champ considéré! !!!
### =============================================================================
#  bcp plus rapide avec les lignes suivantes, mais c'est le nombre de cmip5/6 dans la liste générale
#n_cmip5 = len([ii for ii, x in enumerate(list_exp_id_dxdydz) if 'cmip5' in x['exp']])
#n_cmip6 = len([ii for ii, x in enumerate(list_exp_id_dxdydz) if 'cmip6' in x['exp']])
#n_trop =  len([ii for ii, x in enumerate(list_exp_id_dxdydz) if 'trop'  in x['exp']])

print('\n1er passage sur la liste list_exp_id_dxdydz pour savoir combien de cmip5 / cmip6 dispo pour ce champ')

for ii in range(len(list_exp_id_dxdydz)) :

   #-------------------------------------------------------------------------------
   #@@     for each exp_name...
   #-------------------------------------------------------------------------------
   exp_name=list_exp_id_dxdydz[ii]['exp']

#  if debug : print(exp_name)

   ###   read :
   ###      Bank of images 
   ###      List of image to display for each exp
   ###      img_dic_list
   ###      img_selected_list
   with open('./'+subdir+'/'+img_pattern_file) as f2: exec(f2.read())

   ii_test_exists = [ii for ii, x in enumerate(img_dic_list) if x['name'] == img_test_exists][0]
   ###   test si l'image 1 (PRE-PROCESS.nc) existe / sinon sort de la boucle
   if not(os.path.exists('./images/'+img_dic_list[ii_test_exists]['exp'] )) : 
#     print (exp_name+' : the first image for '+var1+' does not exist')
#     print ('ii_cmip5', ii_cmip5)
      continue

   if 'cmip5'   in exp_name : n_cmip5+=1
   elif 'cmip6' in exp_name : n_cmip6+=1
   elif 'trop'  in exp_name : n_trop+=1

print ('\npour ', var1,':')
print ('   n_cmip5 : ', n_cmip5)
print ('   n_cmip6 : ', n_cmip6)
print ('   n_trop : ', n_trop)
### =============================================================================



print('\n2eme passage sur la liste list_exp_id_dxdydz pour traiter chaque exp')

ii_num_header=0

print('\nPWD : ',os.getcwd(),'\n')


for ii in range(len(list_exp_id_dxdydz)) :

   #-------------------------------------------------------------------------------
   #@@     for each exp_name...
   #-------------------------------------------------------------------------------
   exp_name=list_exp_id_dxdydz[ii]['exp']

   if debug : print(exp_name)

   ###   read :
   ###      Bank of images 
   ###      List of image to display for each exp
   ###      img_dic_list
   ###      img_selected_list
   with open('./'+subdir+'/'+img_pattern_file) as f2: exec(f2.read())

   ii_test_exists = [ii for ii, x in enumerate(img_dic_list) if x['name'] == img_test_exists][0]
   ###   test si l'image 1 (PRE-PROCESS.nc) existe / sinon sort de la boucle
   if not(os.path.exists('./images/'+img_dic_list[ii_test_exists]['exp'] )) : 
      print (exp_name+' : the first image for '+var1+' does not exist')
      print ('     ','./images/'+img_dic_list[1]['exp'] )
      continue

   if 'cmip5'   in exp_name : ii_cmip5+=1; num_str='(%d/%d)'%(ii_cmip5,n_cmip5); color1='#e2ffd7'
   elif 'cmip6' in exp_name : ii_cmip6+=1; num_str='(%d/%d)'%(ii_cmip6,n_cmip6); color1='#d7fffb'
   elif 'trop'  in exp_name : ii_trop+=1;  num_str='(%d/%d)'%(ii_trop,n_trop);   color1='#fffed7'
   else                     :              num_str='';                           color1='#f8e3ff'

   num_col_total=len(img_selected_list)

   ###   create header
   str1='<tr>\n'
   str2='<tr>\n'
   for num_img in range (len(img_selected_list)) :
      for jj in range (len(img_dic_list)) :
         if img_dic_list[jj]['name'] == img_selected_list[num_img] :
#           print  (img_dic_list[jj]['name'])
            header01=img_dic_list[jj]['header1']
            header02=img_dic_list[jj]['header2']
            str1=str1+'<td align="center" rowspan="1" colspan="1" style="background-color: #ffffff">'+header01+'</td>\n'
            str2=str2+'<td align="center" rowspan="1" colspan="1" style="background-color: #ffffff">'+header02+'</td>\n'
   str1=str1+'</tr>\n'
   str2=str2+'</tr>\n'


   ###    print header (every 4 exp)
   if ii_num_header%num_header == 0 : f1.write(str1);  f1.write(str2)


   ###   print the number & the name of the exp  (every num_col columns) 
   ###      ex : n°33/46: cmip5_IPSL-CM5A-MR_historical_19890101-20051231_Omon_1m_r1i1p1_thetao
   for jj in range(num_col_total) :
#     print(jj, num_col, jj%num_col)
      if (jj%num_col == 00) : 
         if (num_col_total-jj) >= num_col : 
            f1.write('<td align="center" rowspan="1" colspan="'+str(num_col)+'" style="background-color: #ffffff">'+num_str+' <span class="stabilo2">'+exp_name+'</span></td>\n')

   f1.write('</tr>\n')
   f1.write('<tr>\n')


   ###   display all images for the exp
   for num_img in range (len(img_selected_list)) :
      for jj in range (len(img_dic_list)) :
         exp_file=img_dic_list[jj]['exp']
         if img_dic_list[jj]['name'] == img_selected_list[num_img] :
            f1.write('<td style="background-color: '+color1+'"><a href="javascript:;" onclick="ChargeImage1(\''+img_root_dir+exp_file+'\');">\n')
            f1.write('    <img class="image1" src=\''+img_root_dir+exp_file+'\' /></a></td>\n')


   f1.write('</tr>\n')

   ii_num_header+=1



html_template_end = """
  <tr>
  </tr>
  </tbody>
</table>

   <!--=================================== Pied de page  ===================================-->
   <br />
   <br />
   <br />

   <table width="100%" border="1px">
      <tbody>
         <tr>
            <td align="center">Webmaster: christophe.hourdin @ locean-ipsl.upmc.fr</td>
         </tr>
         <tr>
            <td align="center">Croco-Agrif-Pisces Projects - <a href="https://pagesperso.locean-ipsl.upmc.fr/cholod/EUC_Upwelling/index.xhtml">Home</a></td>
         </tr>
      </tbody>
   </table>
</body>
</html>
"""


f1.write(html_template_end)

  
# close the file
f1.close()

print('\n\nimg_dic_list available (generated by '+img_pattern_file+') : \n')
for ii in range(len(img_dic_list)) : 
   print(img_dic_list[ii]['name'])

print('\n\nimg_selected_list to be displayed (generated by '+img_pattern_file+') : \n')
print(*img_selected_list,sep = '\n')








