#!/usr/bin/env python3

import argparse
import json
import sys
import config
import node
import espeasy
import pydoc
import util
from espcore import *


def get_epilog():
    docs=pydoc.render_doc(node.Node) + pydoc.render_doc(espeasy.EspEasy)

    docs=docs+"""
Examples:

Build, flash and connect to serial for node 1:
    ./espcli node 1 bfs

Build and flash all configured nodes:
    ./espcli node all bf

Configure wifi settings for node:
    ./espcli node 0 wificonfig

Configure node 0, controller 1 as domoticz mqtt:
    ./espcli espeasy 0 controller_domoticz_mqtt index=1 controllerip=1.2.3.4

    """
    return(docs)

parser = argparse.ArgumentParser(description='ESPEasy testing CLI', epilog=get_epilog(), formatter_class=argparse.RawDescriptionHelpFormatter)

# parser.add_argument('--url', default='http://localhost:8080/rpc', help='url of rpc server to connect to. default: %(default)s')
# parser.add_argument('--user', default=None, help='user to login.')
# parser.add_argument('--password', default=None, help='password.')
# parser.add_argument('--api_key', default=None, help='api_key, use instead of password to overrule all logins globally')
# parser.add_argument('--upload', default=None, help='File to upload')
# parser.add_argument('--json', action='store_true', help='interpret parameters as raw JSON data. (usefull when you want to pass complexer data type like subarrays or dicts) dont forget to use single quotes around the json string.')
# parser.add_argument('--short', action='store_true', help='return short single-line JSON output (for scripting)')
# parser.add_argument('--verbose', action='store_true', help='request verbose mode (module help output)')
# parser.add_argument('--insecure', action='store_true', help='dont verify SSL certificates. (use with self-signed certificates)')
parser.add_argument('--debug', action='store_true', help='enable http debugging output')

parser.add_argument('module',      nargs=1, help='Module to use (node or espeasy)')

node_choices=['all']
for node_choice in range(0,len(config.nodes)):
    node_choices.append(str(node_choice))
parser.add_argument('node',   choices=node_choices,nargs=1, help='Node number (from config)')

parser.add_argument('command',      nargs=1, help='Function from the module (help below)')
parser.add_argument('params',  default=[], nargs='*', help='command parameters. in foo=bar form ')

args = parser.parse_args()

try:

    if args.debug:
        util.enable_http_debug()


    #which node to process? all or a specific one?
    if args.node[0]=='all':
        node_indexes=range(0,len(config.nodes))
    else:
        node_indexes=[int(args.node[0])]

    #traverse selected nodes
    for node_index in node_indexes:
        node_instance=node.Node(config.nodes[node_index], "node"+str(node_index))


        #determine rpc parameters
        params={}
        for param in args.params:
            (key,value)=param.split("=")
            params[key]=value

        if args.module[0]=='node':
            command = getattr(node_instance, args.command[0])
            command(**params)

        elif args.module[0]=='espeasy':
            espeasy_instance=espeasy.EspEasy(node_instance)
            command = getattr(espeasy_instance, args.command[0])
            command(**params)
        else:
            raise(Exception("Unknown module:"+args.module[0]))

    sys.exit(0)

except Exception as e:
    log.error(str(e))
    if args.debug:
        print()
        print("Details:")
        raise
    sys.exit(1)
