#
# This script creates an HTML file containing a list of the NUG
# examples and their graphics if any. The NUG files will likely
# be ordered by the order they appear in the NUG document.
# 
# The NUG example scripts are installed in
# $NCARG_ROOT/lib/ncarg/nclex/nug
#
import os, sys, glob, datetime

# Create directory for running NUG examples
def create_tmp_nug_dirs():
#  tmp_dir = os.path.abspath(datetime.datetime.now().strftime('nug_tmp_%Y-%m-%d_%H:%M:%S'))
  tmp_dir = os.path.abspath('nug_tmp')
  img_dir = tmp_dir + "/Images" 
  scp_dir = tmp_dir + "/Scripts"
  if not os.path.exists(tmp_dir):
    os.mkdir(tmp_dir)
  if not os.path.exists(scp_dir):
    os.mkdir(scp_dir)
  if not os.path.exists(img_dir):
    os.mkdir(img_dir)
  return([tmp_dir,scp_dir,img_dir])

# Read in file containing NUG examples and descriptions
# and return a dictionary.
def get_nug_dict(cdir,nug_file):
  from collections import OrderedDict
  nug_dict = OrderedDict()
  cdir_file = os.path.join(cdir,nug_file)
  if not os.path.exists(cdir_file):
    print("get_nug_dict: '%s' doesn't exist, can't continue" % nug_file)
    sys.exit(2)

  lines = open(cdir_file).readlines()
  for nl in range(len(lines)):
    if(lines[nl][0:3] == "NUG"):
      nug_name = lines[nl].split('\n')[0]
      nug_desc = lines[nl+1].split('\n')[0]
#     print("Name: '%s'" % nug_name)
#     print("Desc: '%s'" % nug_desc)
      nug_dict[nug_name] = nug_desc
  return(nug_dict)

# Create soft links to required data files for NUG examples
def softlink_required_data_files(data_dir,scp_dir):
    file_types = ('*.bin', '*.nc', '*.txt', 'DEU_adm', '*.jpg')  # the tuple of file types
    os.chdir(data_dir)
    data_files = []
    for files in file_types:
      data_files.extend(glob.glob(files))
    os.chdir(scp_dir)
    for dfile in data_files:
      os.system("ln -s %s/%s %s" % (data_dir,dfile,dfile))

# Create large PNG image.
def create_large_png(scp_dir,img_dir,orig_name,large_name):
  cmd = "convert -trim -geometry 1000x1000 +repage -border 8 -bordercolor white -background white -flatten %s/%s %s/%s" % (scp_dir,orig_name,img_dir,large_name)
  os.system(cmd)

# Create thumbnail PNG image.
def create_small_png(img_dir,large_name,small_name):
  cmd = "convert -geometry 100x100 -contrast %s/%s %s/%s" % (img_dir,large_name,img_dir,small_name)
  os.system(cmd)

# Post-process PNG images to create large and small versions
def process_png_images(scp_dir,img_dir,nug_name):
  os.chdir(scp_dir)
  if(os.path.exists("%s.png" % nug_name) or
     os.path.exists("%s.000001.png" % nug_name)):
     png_files = sorted(glob.glob("%s*.png" % nug_name))
     nfiles = len(png_files)
     counter = 1
     for png_file in png_files:
       if(nfiles == 1):
         large_png_file = "%s_lg.png" % (nug_name)
         small_png_file = "%s_sm.png" % (nug_name)
       else:
         large_png_file = "%s_%d_lg.png" % (nug_name,counter)
         small_png_file = "%s_%d_sm.png" % (nug_name,counter)
         counter = counter+1
       create_large_png(scp_dir,img_dir,png_file,large_png_file)
       create_small_png(img_dir,large_png_file,small_png_file)

# Run NUG NCL examples and process PNG images
def run_nug_examples(data_dir,nug_dir,scp_dir,img_dir,nug_dict):
  img_dir = nug_dir + "/Images" 
  scp_dir = nug_dir + "/Scripts"
  softlink_required_data_files(data_dir,scp_dir)
  for nug_name in nug_dict.keys():
    os.chdir(scp_dir)
    os.system("ng4ex %s" % nug_name)
    process_png_images(scp_dir,img_dir,nug_name)

# Write a header stuff needed for NCL Applications page
def write_apps_page_header(f):
  f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n')
  f.write('	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n')
  f.write('	<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">\n')
  f.write('<head>\n')
  f.write('<meta name="description" content="NCL User Guide examples">\n')
  f.write('<meta name="keywords" content="NCL, user guide, graphics, visualization, file I/O, interpolation">\n')
  f.write('<title>NCL User Guide Examples</title>\n')
  f.write('</head>\n\n')
  f.write('<body>\n\n')
  f.write('	<!-- main navigation include -->\n')
  f.write('	<!--#include virtual="/includes/head.html" -->\n')
  f.write('	<!--#include virtual="/includes/ncl.html" -->\n\n')
  f.write('	<div id="wrap"><!-- begin wrap -->\n')
  f.write('	<div id="content"><!-- begin content -->\n\n')
  f.write('	<!-- ######### BEGIN EDITABLE PAGE CONTENT ######### -->\n\n')
  f.write('			<div id="subheader"><!-- begin subheader -->\n')
  f.write('			<!--#include virtual="/includes/nclsubheader.html" -->\n')
  f.write('			</div><!-- end subheader -->\n\n')
  f.write('			      <div id="general_main">\n\n')
  f.write('   <!--#include virtual="./crumb_dataP.html"--><br>\n')
  f.write('   <h1>NCL User Guide examples</h1>\n')

# Write a intro stuff needed for NCL Applications page
def write_apps_page_intro(f):
  f.write('<div class=mainimage>\n')
  f.write('<img width=500 height=500 src="Images/NUG_globe_orography_grid_resolution_lg.png">\n')
  f.write('</div>\n\n')
  f.write('<div class=text>\n\n')
  f.write('These are some of the NCL examples referenced in the NCL User Guide, in the\n')
  f.write('order they appear in the guide. To copy and run any of these examples from a\n')
  f.write('UNIX terminal window, type:\n\n')
  f.write('<pre>\n')
  f.write('   ng4ex <i>xxxxxxx</i>\n')
  f.write('</pre>\n\n')
  f.write('where <i>xxxxxxx</i> is the name of the example with out the ".ncl" suffix, for\n')
  f.write('example, "NUG_curvilinear_grid".  Some of these example require one or more data files,\n')
  f.write('which you can download from\n')
  f.write('<a href="/Document/Manuals/NCL_User_Guide/Data/">http://www.ncl.ucar.edu/Document/Manuals/NCL_User_Guide/Data/</a>.\n')
  f.write('</div>\n\n')

# Count number of PNG images with "_lg.png" in the name
def count_lg_png_names(img_dir,nug_name):
  # First check for single PNG image
  png_file = "%s_lg.png" % nug_name
  if(os.path.exists("%s/%s" % (img_dir,png_file))):
    return(1)
  else:
    # Now check for multiple PNG images
    png_file = "%s_1_lg.png" % nug_name
    if(os.path.exists("%s/%s" % (img_dir,png_file))):
      png_files = glob.glob("%s/%s_[0-9]_lg.png" % (img_dir,nug_name))
      return(len(png_files))
  return(0)

# Write <div>...</div> section for NUG example
def write_apps_page_examples(f,img_dir,nug_dict):
  for nug_name in nug_dict.keys():
    nfiles = count_lg_png_names(img_dir,nug_name)
    nug_name_ncl = nug_name + ".ncl"
    f.write('<div class=ex>\n')
    f.write('<!--%s-->\n' % nug_name)
    f.write('<a name=%s></a>\n' % nug_name)
    if(nfiles == 1):
      f.write('<a href="Images/%s_lg.png">\n' % nug_name)
      f.write('<img src="Images/%s_sm.png" align=left border=2></a>' % nug_name)
    elif(nfiles > 1):
      limit = 3
      for i in range(min(limit,nfiles)):
        f.write('<a href="Images/%s_%d_lg.png">\n' % (nug_name,(i+1)))
        f.write('<img src="Images/%s_%d_sm.png" align=left border=2></a>\n' % (nug_name,(i+1)))
    f.write('<a href="Scripts/%s">%s</a>:\n' % (nug_name_ncl,nug_name_ncl))
    f.write(nug_dict[nug_name])
    f.write('<p>\n')
    if(nfiles == 0):
      f.write('This example does not produce any graphics.<p>\n')
    f.write('</div>\n\n')


# Write a footer for an HTML file
def write_apps_page_footer(f):
  f.write('					</div>\n\n')
  f.write('					<p>&nbsp;</p>\n\n')
  f.write('		<!-- begin footer -->\n')
  f.write('		<div id="footer">\n\n')
  f.write('		<!--#include virtual="/includes/nclfooter.html" -->\n\n')
  f.write('		<!-- end footer -->\n')
  f.write('		</div>\n\n')
  f.write('           <br class="clearboth"/>\n\n')
  f.write('	   <!-- end content -->\n')
  f.write('	</div>\n')
  f.write('<!-- end wrap -->\n')
  f.write('</div>\n')
  f.write('</body>\n')
  f.write('</html>\n')

# Create an apps page for the NUG examples
def write_apps_page(nug_dir,img_dir,nug_dict):
  os.chdir(nug_dir)
  f = open("NUG.xml","w")
  write_apps_page_header(f)
  write_apps_page_intro(f)
  write_apps_page_examples(f,img_dir,nug_dict)
  write_apps_page_footer(f)

#----------------------------------------------------------------------
# Main driver
#----------------------------------------------------------------------
current_dir = os.getcwd()
data_dir = "/Users/haley/webdoc/ncl/Document/Manuals/NCL_User_Guide/Data"
[nug_dir,scp_dir,img_dir] = create_tmp_nug_dirs()
nug_dict = get_nug_dict(current_dir,"nug_list")
RUN_EXAMPLES = False
if(RUN_EXAMPLES):
  run_nug_examples(data_dir,nug_dir,scp_dir,img_dir,nug_dict)
write_apps_page(nug_dir,img_dir,nug_dict)
