#!/usr/bin/env python
from __future__ import print_function
import os, datetime, sys

INVALID=''

MY_DIR = os.path.split(__file__)[0]

JEKYLL_TEMPLATE="""---
layout: default
title: Index of {pathname}
---
{table_html}
"""


TEMPLATE="""<!DOCTYPE HTML>
<html>
 <head>
  <title>Index of {pathname}</title>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
 </head>
 <body>
  <div class="container-fluid">

   <div class="row">
    <div class="text-center">
     <h1>Index of {pathname}</h1>
    </div>
   </div>

   <div class="row">
    <div class="col-md-10 col-md-offset-1">

     <div id="static_site_index_html_index">{table_html}</div>
     <div id="static_site_index_js_index" style="display:none;visibility:hidden;">
      {angular_template}
     </div>
    </div>
   </div>

   <div class="row">
    <div id="static_site_index_blurb" class="text-center col-md-10 col-md-offset-1">Page generated by <a href="https://github.com/astraw/static_site_index">github.com/astraw/static_site_index</a>.</div>
   </div>

  </div>
<script>
{js_file}
</script>
</body></html>
"""

def get_html_table_buf(html_elements):
    table_bufs = []
    table_bufs.append('<table id="static_site_index_html_table" class="table table-responsive table-condensed table-striped">')
    table_bufs.append('<thead><tr>' +
                      '<th></th><th>Name</th><th>Last modified</th><th>Size</th>' +
                      '</tr></thead><tbody>')

    tab_fmt = ('<tr>'
               '<td data-faname={fa_name}><i class="fa fa-{fa_name} fa-fw"></i></td>'
               '<td><a href="{link}">{name}</a></td>'
               '<td data-mtime="{lastmodified}">{lastmodified_human}</td>'
               '<td>{size}</td>'
               '</tr>')

    for html_element_data in html_elements:
        table_bufs.append(tab_fmt.format(**html_element_data))

    table_bufs.append('</tbody></table>')

    return '\n'.join(table_bufs)

def write_index(fname,elements,parent_link,pathname,jekyll=False):
    html_elements = [{
        'name':'.. (Parent Directory)',
        'link':parent_link,
        'lastmodified':INVALID,
        'lastmodified_human':'',
        'size':INVALID,
        'fa_name':'level-up',
        }] + elements

    table_html = get_html_table_buf(html_elements)

    index_js_fname = os.path.join(MY_DIR,'index.js')
    template_content_fname = os.path.join(MY_DIR,'template.html')
    js_file = open(index_js_fname,mode='r').read()

    # based on http://codepen.io/anon/pen/fjkcg
    angular_template = open(template_content_fname,mode='r').read()

    if jekyll:
        buf = JEKYLL_TEMPLATE.format( **locals() )
    else:
        buf = TEMPLATE.format( **locals() )
    with open(fname, mode='w') as fd:
        fd.write(buf)

def modtime_str(t):
    r = datetime.datetime.fromtimestamp(t)
    fmt = '%d-%b-%Y %H:%M'
    result = r.strftime(fmt)
    return result

def make_index(parent_link,pathname,jekyll=False,recursive=True):
    files = os.listdir(os.curdir)
    files.sort()
    elements = []
    for f in files:
        if f=='index.html':
            continue
        attrs = os.stat(f)
        mtime = attrs.st_mtime
        sz = attrs.st_size
        link = os.path.join( pathname, f )
        el = {
            'name':f,
            'link':link,
            'lastmodified':mtime,
            'lastmodified_human':modtime_str(mtime),
            'size':sz,
            }
        if os.path.isdir(f):
            el['name']=el['name']+'/'
            el['fa_name']='folder'
            el['size']=INVALID
            subdir = pathname + '/' + f
            if subdir.startswith('//'):
                subdir = subdir[1:] # trim leading double slash
            mdfile = os.path.join(f,'index.markdown')
            if not os.path.exists(mdfile):
                if recursive:
                    do_index(f, pathname, subdir, jekyll=jekyll, recursive=recursive)
        elif os.path.isfile(f):
            el['fa_name']='file'
        else:
            raise ValueError('unknown dir entry: %r'%f)
        elements.append(el)
    write_index('index.html',elements,parent_link,pathname,jekyll=jekyll)

def do_index(filesystem_dirname, parent_link=None, this_url_path=None,
             jekyll=False, recursive=True):
    if this_url_path is None:
        this_url_path = '/'
    orig_dir = os.path.abspath(os.curdir)
    os.chdir( filesystem_dirname )
    try:
        make_index(parent_link, this_url_path,
                   jekyll=jekyll,
                   recursive=recursive)
    finally:
        os.chdir( orig_dir )

if __name__=='__main__':
    print('create_index called from command line')
    BASE_DIR = sys.argv[1]
    print('  BASE_DIR = %r'%BASE_DIR)
    do_index(BASE_DIR)
