#!/usr/bin/env python


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

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

debug=True

var1='wo' ;       project_list=['cmip6']


html_filename='atlas'

title1='wo / wod Comparison'

img_pattern_name='img_pattern'

F_from_exp_list=False
exp_list_name='cmip6_HR'

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


img_root_dir='../images/'

###   where to generate the exp_list: 
search_dir='../images/EUC_Upwelling_characterize/PERU.'+var1+'.SAV'
suffix='_PERU_'+var1+'_sst.pcf025.zip.png'
separateur="_PERU_"

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


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

   
#===============================================================================
#@   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/rejected lists infos :
   with open('exp_list-'+exp_list_name+'.py') as f0: exec(f0.read())

   ###   we bypass the “for each project” loop because just the selected_list counts
   project_list=['cmip5']

   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(script_dir+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 - 
#-------------------------------------------------------------------------------







os.chdir(search_dir)
iproject=0
nn=0
#-------------------------------------------------------------------------------
#@@     for each project (cmip5, cmip6, woa23)...
#-------------------------------------------------------------------------------
for project in project_list :
   ii=1
   

   #-------------------------------------------------------------------------------
   #@@     for each exp_file...
   #-------------------------------------------------------------------------------

   if F_from_exp_list :
      exp_file_list=selected_list
   else :
      exp_file_list=sorted(glob.glob(project+'*'+suffix))

   for exp_file in exp_file_list :

      wod_file=exp_file.replace('wo','wod')
#     os.system('ls ../PERU.wod.SAV/'+wod_file)
      if os.path.exists(exp_file) & os.path.exists('../PERU.wod.SAV/'+wod_file) :
         exp_name=exp_file.split(separateur)[0]
         print(exp_file,':')
         if debug : print(exp_name)
   
   
         ###   The color definition must be here, because if from_exp_list=true the “for each project” loop is bypassed.
         color1='#f8e3ff'
         if 'cmip5' in exp_name : color1='#e2ffd7'
         if 'cmip6' in exp_name : color1='#d7fffb'
         if 'trop'  in exp_name : color1='#fffed7'
   
   
         ###   read :
         ###      Bank of images 
         ###      List of image to display for each exp
         with open(script_dir+img_pattern_name+'.py') as f2: exec(f2.read())
   
   
         num_col_total=len(img_list)
   
   
         ###   create header
         str1='<tr>\n'
         str2='<tr>\n'
         for num_img in range (len(img_list)) :
            for jj in range (len(ls)) :
               header01=ls[jj]['header1']
               header02=ls[jj]['header2']
               if ls[jj]['name'] == img_list[num_img] :
                  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 nn%4 == 0 : f1.write(str1);  f1.write(str2)
   
   
         ###   compute the number of the exp in the project : 
         ###      ex : n°33/46
         if F_from_exp_list :
            ii_exp=str(ii)
         else :
            num_exp_total=len (glob.glob(project+'*'+suffix))      
            ii_exp=str(ii)+'/'+str(num_exp_total)
   
   
         ###   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">n°'+ii_exp+': <span class="stabilo2">'+exp_file.replace(suffix,'')+'</span> ('+str(iproject)+')</td>\n')
      
         f1.write('</tr>\n')
         f1.write('<tr>\n')
   
   
         ###   display all images for the exp
         for num_img in range (len(img_list)) :
            for jj in range (len(ls)) :
               exp_file00=ls[jj]['exp']
               if ls[jj]['name'] == img_list[num_img] :
                  f1.write('<td style="background-color: '+color1+'"><a href="javascript:;" onclick="ChargeImage1(\''+img_root_dir+exp_file00+'\');">\n')
                  f1.write('    <img class="image1" src=\''+img_root_dir+exp_file00+'\' /></a></td>\n')
   
   
         f1.write('</tr>\n')
         ii=ii+1
         nn=nn+1
      iproject=iproject+1
   
   

os.chdir(script_dir)


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()









