__author__ = 'RemiZOffAlex'
__email__ = 'remizoffalex@mail.ru'

import sys
import json
import argparse
import traceback

from .. import app
from ..api import jsonrpc


def main():
    parser = argparse.ArgumentParser(
        description='API',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser._optionals.title = "Необязательные аргументы"

    parser.add_argument("--json-rpc", help="JSON-RPC")
    parser.add_argument("--methods", action='store_true')
    parser.add_argument("--example")
    parser.add_argument("--verbose", action='store_true')
    parser.add_argument("--save")

    args = parser.parse_args()

    if args.json_rpc:
        request = json.loads(args.json_rpc)
        if args.verbose:
            app.logger.info(request)
        result = jsonrpc(request)
        if args.save:
            with open(args.save, 'w') as fd:
                fd.write(result)
        print(result)

    if args.methods:
        print(jsonrpc.methods)
        print('[{0}]'.format(', '.join(jsonrpc.methods)))

    if args.example:
        result = jsonrpc.example(args.example)
        print(json.dumps(result))


try:
    main()
except Exception as err:
    traceback.print_exc(file=sys.stdout)
    exit(1)
