# coding: utf-8
"""Usage:
  avtograf [init|run] [--src <PATH>] [--debug] [--version]

--src  path to the data

Support: leroy, n-bar
"""
import traceback
import os

from library.python.svn_version import svn_version
from docopt import docopt

from tsv2db import main as cmd_init
from avtograf import main as cmd_run


DESC_FNAME = 'info'
DB_NAME = 'source.db'
TBL_NAME = 'data'
SRC_NAME = 'data'
DST_DIR = 'Result'
LOG_FILE = '.logerror.log'


def cmds(args):
    if not args["init"] and not args["run"]:
        if os.path.exists(DB_NAME) and os.path.exists("%s.xlsx" % DESC_FNAME):
            args["init"] = False
            args["run"] = True
        else:
            args["init"] = True
            args["run"] = False

    if args["init"]:
        print "init...",
        cmd_init(
            DB_NAME,
            TBL_NAME,
            args["<PATH>"] or SRC_NAME,
            DESC_FNAME,
        )
        print "done"

    if args["run"]:
        print "run...",
        cmd_run(DB_NAME, DESC_FNAME, DST_DIR)
        print "done"
    print "exit"


def main():
    try:
        SV_VER = svn_version()
        args = docopt(__doc__, version=SV_VER)
        if args.get("--debug"):
            with open(LOG_FILE, "w") as f:
                f.write("\nVERSION\n:%s\n" % SV_VER)
                f.write("\nCLI ARGS\n:%r\n" % args)
        cmds(args)
    except Exception as err:
        print "error: %s" % err.message
        with open(LOG_FILE, 'a') as f:
            traceback.print_exc(file=f)


if __name__ == "__main__":
    main()
