#!/usr/bin/env python
#coding=utf-8
"""
Author:         Xia Kai <xiaket@gmail.com>
Filename:       Snape
Date created:   2016-07-06 20:58
Last modified:  2016-07-06 21:32
Modified by:    Xia Kai <xiaket@gmail.com>

Description:
    A commandline snippet manager.
Changelog:
"""
import json
import os
import readline
import sys


USAGE = """
Usage:
    snape                       # list all snippet with descriptions.
    snape Name of snippet       # show the single snippet.
    snape add Name of snippet   # add a snippet
"""
DBFILE = os.path.expanduser("~/.snape.json")


def load_db():
    if not os.path.isfile(DBFILE):
        return {}
    with open(DBFILE) as fobj:
        db = json.loads(fobj.read())
    return db

def list_all(db):
    for name in sorted(db.keys()):
        print "%% %s %%" % name
        print db[name]

def add(db, name):
    print "Enter/Paste your content. Ctrl-D to save it."
    contents = []
    while True:
        try:
            line = raw_input("")
        except EOFError:
            break
        contents.append(line)

    db[name] = "\n".join(contents)
    with open(DBFILE, 'w') as fobj:
        fobj.write(json.dumps(db, indent=2))
    return db

def main():
    db = load_db()
    if len(sys.argv) == 1:
        list_all(db)
    else:
        rest = " ".join(sys.argv[1:])
        first = sys.argv[1]
        if rest in db:
            print "%s: \n%s" % (rest, db[rest])
        elif first == "add" and len(sys.argv) > 2:
            add(db, " ".join(sys.argv[2:]))
        else:
            print USAGE
            sys.exit(1)


if __name__ == '__main__':
    main()
