#!/usr/bin/env python3

__author__ = 'RemiZOffAlex'
__copyright__ = '(c) 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", action='store_true')
    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:
        print(jsonrpc.example)


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

    exit(0)
