"""Command line interface for rflink library.

Usage:
  rflink [-v | -vv] [options]
  rflink [-v | -vv] [options] ( on | off) <id>
  rflink (-h | --help)
  rflink --version

Options:
  -p --port=<port>   Serial port to connect to [default: /dev/ttyACM0],
                       or TCP port in TCP mode.
  --baud=<baud>      Serial baud rate [default: 57600].
  --host=<host>      TCP mode, connect to host instead of serial port.
  -m=<handling>      How to handle incoming packets [default: event].
  --ignore=<ignore>  List of device ids to ignore, end with * to match wildcard.
  -h --help          Show this screen.
  -v                 Increase verbosity
  --version          Show version.

"""

import asyncio
import logging
import sys

import pkg_resources
from docopt import docopt

from .protocol import (
    EventHandling,
    InverterProtocol,
    PacketHandling,
    RepeaterProtocol,
    RflinkProtocol,
    create_rflink_connection
)

PROTOCOLS = {
    'command': RflinkProtocol,
    'event': EventHandling,
    'print': PacketHandling,
    'invert': InverterProtocol,
    'repeat': RepeaterProtocol,
}


def main(argv=sys.argv[1:], loop=None):
    """Parse argument and setup main program loop."""
    args = docopt(__doc__, argv=argv,
                  version=pkg_resources.require('rflink')[0].version)

    level = logging.ERROR
    if args['-v']:
        level = logging.INFO
    if args['-v'] == 2:
        level = logging.DEBUG
    logging.basicConfig(level=level)

    if not loop:
        loop = asyncio.get_event_loop()

    if args['--ignore']:
        ignore = args['--ignore'].split(',')
    else:
        ignore = []

    if args['on']:
        command = 'on'
    elif args['off']:
        command = 'off'
    else:
        command = None

    if command:
        protocol = PROTOCOLS['command']
    else:
        protocol = PROTOCOLS[args['-m']]

    conn = create_rflink_connection(
        protocol=protocol,
        host=args['--host'],
        port=args['--port'],
        baud=args['--baud'],
        loop=loop,
        ignore=ignore,
    )

    transport, protocol = loop.run_until_complete(conn)

    try:
        if command:
            loop.run_until_complete(
                protocol.send_command_ack(
                    args['<id>'], command))
        else:
            loop.run_forever()
    except KeyboardInterrupt:
        # cleanup connection
        transport.close()
        loop.run_forever()
    finally:
        loop.close()

@@ -106,16 +106,36 @@
 options%5D
+ %5B--repeat %3Crepeat%3E%5D
  ( on %7C 
@@ -443,16 +443,81 @@
 l port.%0A
+  --repeat=%3Crepeat%3E  How often to repeat a command %5Bdefault: 1%5D.%0A
   -m=%3Cha
@@ -2234,32 +2234,87 @@
     if command:%0A
+            for _ in range(int(args%5B'--repeat'%5D)):%0A    
             loop
@@ -2334,16 +2334,20 @@
 mplete(%0A
+    
         
@@ -2381,16 +2381,20 @@
 nd_ack(%0A
+    
         

Add repetition.