#!/usr/bin/python
# coding: utf8

# PyIndex
# author: Ondrej Sika, http://ondrejsika.com, ondrej@ondrejsika.com


import os
import time
import json

def index(path):
    data = []
    for node in os.listdir(path):
        node_path = os.path.join(path, node)
        try:
            stat = os.stat(node_path)
            data.append({
                "name": node,
                "type": "d" if os.path.isdir(node_path) else "f",
                "size": stat.st_size,
                "created": stat.st_mtime,
                "created_str": time.asctime(time.gmtime(stat.st_mtime)),
            })
        except OSError:
            continue
    return data


def as_json(index):
    return json.dumps(index)

def as_html(index):
    out = """
        <table>
        <tr>
            <th style="min-width:300px">name</th>
            <th style="min-width:40px">type</th>
            <th style="min-width:50px">size</th>
            <th style="">created</th>
        </tr>
    """
    for node in index:
        out += """
            <tr>
                <td><a href="%(name)s">%(name)s</a></td>
                <td>%(type)s</td>
                <td>%(size)s</td>
                <td>%(created_str)s</td>
            </tr>
        """ % node
    out += """
        </table>
        <p>Created by <a href="http://github.com/sikaondrej/pyindex">PyIndex</a></p>
    """
    return out