#!/usr/bin/env python

import json
import time
import sys
import os
from collections import OrderedDict as dict


def json_to_js(json_path, js_path):
    """Convert `commands.json` to `commands.js`"""
    keys = []
    with open(json_path) as fp:
        _json = json.load(fp)
        for k in _json.keys():
            keys.append(k.encode('utf-8'))
    with open(js_path, "w") as fp:
        generate_time(fp)
        fp.write("module.exports = [\n")
        for k in sorted(keys):
            fp.write('\t"%s",\n' % k.lower())
        fp.write("]")


def json_to_go_array(json_path, go_path):
    g_fp = open(go_path, "w")
    with open(json_path) as fp:
        _json = json.load(fp)
        generate_time(g_fp)
        g_fp.write("package main\n\nvar helpCommands = [][]string{\n")
        _json_sorted = dict(sorted(_json.items(), key=lambda x: x[0]))
        for k, v in _json_sorted.iteritems():
            g_fp.write('\t{"%s", "%s", "%s"},\n' % (k, v["arguments"], v["group"]))
        g_fp.write("}\n")
    g_fp.close()


def generate_time(fp):
    fp.write("//This file was generated by .tools/generate_commands.py on %s \n" %
             time.strftime('%a %b %d %Y %H:%M:%S %z'))


if __name__ == "__main__":
    usage = """
    Usage: python %s src_path dst_path"

    1. for Node.js client:

        python generate.py /path/to/commands.json /path/to/commands.js

    2. for cmd/ledis_cli/const.go
        
        python generate.py /path/to/commands.json /path/to/const.go

    """

    if len(sys.argv) != 3:
        sys.exit(usage % os.path.basename(sys.argv[0]))

    src_path, dst_path = sys.argv[1:]
    dst_path_base = os.path.basename(dst_path)

    if dst_path_base.endswith(".js"):
        json_to_js(src_path, dst_path)

    elif dst_path_base.startswith("const.go"):
        json_to_go_array(src_path, dst_path)

    else:
        print "Not support arguments"
