##!/usr/bin/python2
## -*- coding: utf-8 -*-


##CREATED: 7/2012
##AUTHOR: MICHAL ODSTRCIL


<%page args="shot, page, default_path" cached="True" cache_dir='mako_modules' />

<%!
    import os, re, datetime
    from pygolem_lite.web import cat, emph, get_page_paths
    from os.path import split, exists
    ###from pygolem_lite.MoinMoin import code2html
    from pygolem_lite import web, Shot, loadconst
    from pygolem_lite.code2html import code2html
%>

<%
title = 'Golem No: ' + str(shot) + ' - the only fully opensource tokamak'
shot = int(shot)

if page == "":
    page =  "home"

allowed_types = "(htm|html|php|template)"  # types allowed for loading as webpage

page_path, base_path, page  = get_page_paths(shot, page, default_path)

page_path_short  = re.sub("^"+default_path+"\/[\d]+\/", "", page_path)
page_path_short  = re.sub("\/\/", "\/", page_path_short + '/')   # remove shots/ + shot_number from path

show_source = re.match(".+\.(py|m|pro|c|sh|template|cfg)$", page)
show_html = re.match(".+\.(htm|html)$", page)

######  setup pygolem loading ###########
web.cData = Shot(shot)
get = web.cData.get_nice
########  setup pygolem loading ###########


def page_list(base,number= None ):
    """ return list of acceptable pages in "base" directory"""
    if show_source:
	sub = ""    # do not replace template ending for source files
    else:
	sub = "(\.template)"

    l =  sorted([ re.sub('(.+)'+sub+'$',r"\1", file) \
    for file in os.listdir( base) \
    if ( re.match(".+\."+allowed_types+"$", file) \
    and  not re.match('.+~', file))])

    if number is not None:
	try:
	    return sorted(l)[number]
	except:
	    return ""
    return l

def get_page_name(name):
    """  remove from page name numbers at beginning and .htm ending"""
    name =   re.sub('(\d+_)(.+)([\.\w]*)$', r'\2',  name)
    name =  re.sub('(.+)\.([\.\w]+)$', r'\1',  name)
    # remove everything before last backslash 
    name =  re.sub('(.+)\/(.+)$', r'\2',  name)
    return name

if page == "":  # if page is directory take the first web page
    page_name = get_page_name(page_list(page_path+'/'+page,0))
else:
    page_name = get_page_name(page)


def make_menu(base, levels, name = ""):
    if base_path in base:
	base =  re.sub(base_path, base_path + "includes/", base)
    else:
	base  =  base_path + base

    try:
	if levels == -1:
	    if name == "":
		name = get_page_name(base)
	    make_item( '/'+ base + '/', name)
	elif levels == 0:   # load directly all html
	    try:
		paths = page_list( base)
		paths = sorted(paths)
		#print "===page list", base, paths
		for item in paths: 
		    name = get_page_name(item)
		    make_item( '/'+ base + '/' +  item, name)
	    except Exception, e:
		print "!!!!!!! local menu failed " + str(e) , base
	else:
	    try:
		paths = sorted( [ '/' +  base +  '/'  + i for i in os.listdir(base) ])
		##print paths 
		for path in paths:
		    print "arerwres ", levels
		    ##print path
		    if levels == 1:
			make_item( path  + '/' , split(path)[-1], -1)
		    elif levels == 2 and os.path.isdir( '.'+path):
			for item in os.listdir( '.'+path):
			    make_item( path+'/'+item+'/' , item, -1)
	    except Exception, e:
		print "!!!!!!!!!  " + str(e), base
    except  Exception, e:
	print "!!!!!!! menu_make failed " + str(e) 


def check_item(path):
    """ Check if the item is allowed in includes directory """
    if base_path in path:
	if not "includes" in path:
	    path =  re.sub(base_path, base_path + "/includes/", path)
	return os.path.exists(path) or os.path.exists(path + ".template") 
	#or os.path.exists('./'+path) or os.path.exists('./'+path + ".template") 
    else:
	return True
%>

<%def name="make_item(path, item, value=None)">
        
    <%
	print "??????????", path
	if not check_item('.'+path):
	    print "check_item", path, "failed"
	    return ""
	else:
	    print "check_item", path, "good"

	
	## remove names, dates, initials
	name  = re.sub('(\d+)([a-zA-Z\ _]+)([\.\w]+)', r'\2',  item)
	name = re.sub('([\w]+)/([a-zA-Z\ ]+)', r'\2',  name)
	path = re.sub('(includes/)(.+)', r'\2',  path)  #  remove includes path from full path 
	#path = re.sub("/"+base_path, '', path)
	
	if value == None:
	    value = 4     # do not show anything
    %>
        
%if value  == -1:
    <%     short_path = re.sub("/"+base_path, '', path) %>

    <?php
    $statusFile = "${  short_path + '/status'}" ;
    $iconFile = "${  short_path + '/icon.png'}" ;
 
    if (file_exists($statusFile) ) {
	$f = fopen($statusFile, 'r');
	$status = fgets($f);
	fclose($f);
	}
    elseif (file_exists($iconFile) ) {
	$status = 0; 
	}
    else  {
	$status = 1; 
	}
    ?>
%else:
    <?php
     $status = ${value};
     ?>
%endif

 <li>
  %if not show_html:
    <?php
    if ( $status == 0 ) {
	echo "&#10003;" ; }
    elseif ( $status == 1 ) {
	echo "&#10005;" ; }
     elseif ( $status == 2 ) {
	echo "?" ; }
    ## working
    elseif ( $status == 3 ) {
	echo "<img src='/_static/AnimationWait.gif' /> ";  }
    elseif ( $status == 4 ) {
	echo "" ; }
    ?>
  %endif

    <a  class="reference internal" href="${path}">${name}</a>
    </li>
</%def>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>${ title } </title>
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="/_static/default.css" type="text/css" />
    <link rel="stylesheet" href="/_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="/_static/lightbox.css" type="text/css" media="screen" />

    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
	URL_ROOT:    '',
	VERSION:     '0.2',
	COLLAPSE_INDEX: false,
	FILE_SUFFIX: '.html',
	HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="/_static/jquery.js"></script>
    <script type="text/javascript" src="/_static/underscore.js"></script>
    <script type="text/javascript" src="/_static/doctools.js"></script>
    <script type="text/javascript" src="/_static/sidebar.js"></script>

    <script src="/_static/lightbox_plus.js"></script>

    ## switch shot number
    <script type="text/javascript">
	function getURL(val){
	location = ${'/'+default_path+'/'} + val + '/' +  "${page_path_short}";
	return false;
	}
    </script>

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>

	<ul>
	<li class="right" ><a href= ${'/'+default_path+'/0' + '/' +  page_path_short  } title="current shot" >current</a> </li>
	<li class="right" ><a href= ${'/'+default_path+'/' + str(shot+1) + '/' + page_path_short} title="next shot" >next</a> |</li>
	<li class="right" ><a href= ${'/'+default_path+'/' + str(shot-1) +  '/' + page_path_short } title="previous shot" >previous</a> | </li>
	</ul>
	<ul>
	<li><a href="/" >  GOLEM  </a> &raquo;
	<a href= ${'/'+default_path+'/'+str(shot)} >Shot  ${"&#35;"+str(shot)}</a>  &raquo;   </li>
	% if page_path is not base_path :
	    ## add one more level to the top menu
	    <li><a href=${'/'+page_path+'/'} >  ${page_name}  </a>	    &raquo;
	%endif
	</ul>
    </div>

    <div class="document">
      <div class="documentwrapper">
	<div class="bodywrapper">
	  <div class="body">
	    <div class="section" >

	    % if page == 'home':
	    <h1>Tokamak GOLEM - Shot Database - ${shot} <a class="headerlink" href="" title="Permalink to this headline"></a></h1>
	    % elif show_source:
		<h1>${ "Source code :: " +   page_name }</a></h1>
	    % else:
		<h1>${ page_name }</h1>
	    %endif

	    ## !!  INCLUDING OTHER WEB PAGES !!!
	    %if show_source:   # generate source code web page
		${ code2html(  page_path+'/'+page ) | trim}
		## include without preprocessing, whitespace trimming,HTML escaping }
	    %elif page in ['home', 'energetics'] :  # base path
		    <a class="viewcode-back" href="${ page + '.php.template'}">${emph("[Template source]")}</a><br/>
		    ##<% print "!"*100 ,  base_path, page %>

		    <%include file="${base_path + page}.php.template"  />
	    %else:
		    <%
			if re.match(".+\."+allowed_types+"$",  page):
			    page_tmp  = page	# link to an allowed type
			else:
			    page_tmp =   page_list(page_path+'/'+page,0)  # in case of link to directory
			index_page =  page_path+'/'+ page_tmp
			page_tmp = re.sub( '(.+)\.php', r'\1',  index_page)
		    %>
		    % if exists(page_tmp) and re.match('.+\.php', index_page):
			${ code2html(  page_path+'/'+page ) | trim}
		    % elif exists(index_page + '.template'):
			## include with mako preprocessing
			<a class="viewcode-back" href="${ '/' +  index_page + '.template'}">${emph("[Template source]")}</a>

			%if os.path.exists(page_path + '/log') and os.path.getsize(page_path + '/log') > 0:
			   <a class="viewcode-back" href="${ 'log'}"> ${emph("[Log]")}</a>
			%endif
			<%
			    print "!"*100
			    print index_page
			    print page_path, page_tmp
			%>
			<%include file="${   index_page  + '.template'}"  />
		    % else:
			## include without preprocessing, whitespace trimming,HTML escaping
			%if os.path.exists(page_path + '/log') and os.path.getsize(page_path + '/log') > 0:
			   <a class="viewcode-back" href="${ 'log'}"> ${emph("[Log]")}</a>
			%endif
			%if os.path.exists(index_page) and not os.path.isdir(index_page):
			    <%  print " generating index page ",   index_page %> 
			    ${cat(index_page, []) | trim}
			%else:
			##%except IOError, msg:
			    <%  print " missing index page ",  index_page  %> 
			    <h4> Some problem during loading of page ${index_page}  </h4>
			    ##Error:${msg} <br>
			    Check if directory contains one of the allowed files ${allowed_types}<br>
			    List of files: <br>
			    <ul>
			    %try:
				%for item in sorted(os.listdir(index_page)):
				    <li> <a href=/${index_page}/${item}>${item}</a>
				%endfor
			    %except:
				pass
			    %endtry
			    </ul>
			##%endtry
			%endif
		    % endif
	    %endif
	    </div>
	  </div>
	</div>
      </div>

      <div class="sphinxsidebar">
	<div class="sphinxsidebarwrapper">


	    <a href= ${'/'+default_path+'/'+str(shot)} ><img src="/_static/logos/golem.svg" alt="" width=80 /></a>


	    % try:

	    % if page in ["home", 'Data.php', 'References.php', "About.php"]:

		<h4>Diagnostics</h4>
		<ul>
		    <% make_menu('diagnostics',2) %>
		</ul>

		<h4>Analysis</h4>
		<ul>
		    <% make_menu('analysis',2) %>
		</ul>

		<h4>DAS</h4>
		<ul>
		    <% make_menu('DAS',1) %>
		</ul>

		<h4>Vacuum log</h4>
		<ul>
		    <% make_menu(base_path + 'nabijeni', -1, 'Charging log') %>
		</ul>

		<h3>Other</h3>
		<ul class="this-page-menu">
		<%
		    make_item('Data.php',  'Data')
		    ##make_item('References.php','References')
		    make_item('http://golem.fjfi.cvut.cz/wiki/Bibliography','References')
		    make_item('About.php','About')
		    make_item('http://golem.fjfi.cvut.cz/wiki/', 'Wiki')
		    make_item('http://golem.fjfi.cvut.cz/utils/', 'Utilities')

		%>
		</ul>

		<h4>Navigation</h4>
		<ul class="this-page-menu">
		<%
		    make_item('/'+default_path+'/' + str(shot+1),  'Next')
		    make_item('/'+default_path+'/' + str(shot-1), 'Previous')
		    make_item('/'+default_path+'/0',  'Current')
		%>
		</ul>

	    %elif not show_source:

		<h4>Menu</h4>
		<ul>
		<%
		    make_menu(page_path, 0)
		%>
		<b>${make_item('/'+default_path+'/' + str(shot), '&laquo; Back to homepage')}</b>
		</ul>

		<h4>Navigation</h4>
		<ul class="this-page-menu">
		<%
      		    make_item('/'+default_path+'/' + str(shot+1) +'/'+ page_path_short,  'Next')
		    make_item('/'+default_path+'/' + str(shot-1) +'/'+ page_path_short ,  'Previous')
		    make_item('/'+default_path+'/0/' +'/'+ page_path_short,  'Current')
		%>
		</ul>
	    %else:
		<h4>Navigation</h4>
		<ul class="this-page-menu">
		    <% make_item("javascript:history.go(-1)", "<b>Return</b>") %>
		</ul>
	    %endif

	    %except:
		<h3> Menu failed </h3>
		##raise
	    %endtry
	    <div id="searchbox" style="display: none">
		<h3>Go to shot</h3>
		    <form  style='display:inline;' method="post" action="" onsubmit="return getURL(this.shot.value)">
		    <input size="5" type="text" name="shot" value="${shot}"  />
		    <input  size="5" type="submit" name="Go" value="Go" />
		    </form>
	    </div>
	    <script type="text/javascript">$('#searchbox').show(0);</script>
	</div>
	</div>
      <div class="clearer"></div>
    </div>

    <%
    # get disk usage of current directory
    try:
        command = "du -ch "+page_path+" | egrep '(celkem|total)'"
	##command = "du -chx  --summarize "+page_path 
	disk_use = re.sub( '([\d\,\.]+\w)(.+\n)', r'\1',  os.popen(command).readline())
    except:
	disk_use = "?"
    %>
    <div class="related">
	<span class="base_template"><a  href="${ '/' + base_path + 'base.php.template'}" title="main template">${"[Main template]"}</a> ${"&nbsp;"*5} ${("Disk usage: "+disk_use+"B")} </span>


    <h3>Navigation</h3>
    <ul>
	 ## remove shot number from path
	<li class="right" ><a href= ${'/'+default_path+'/0' + '/' +  page_path_short  } title="current shot" >current</a> </li>
	<li class="right" ><a href= ${'/'+default_path+'/' + str(shot+1) +  '/' + page_path_short} title="next shot" >next</a> |</li>
	<li class="right" ><a href= ${'/'+default_path+'/' + str(shot-1) + '/' +  page_path_short } title="previous shot" >previous</a> | </li>
    </ul>
    </div>

    <div class="footer">
	&copy; Copyright ${ datetime.datetime.now().year }, <a href="mailto:svoboda@fjfi.cvut.cz">GOLEM Team</a>
    </div>


  <script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-37412576-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

  </script>

  </body>





</html>
