#!/usr/bin/python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division, unicode_literals
##
##  This file is part of etcTree, a dynamic and Pythonic view of
##  whatever information you tend to store in etcd.
##
##  etcTree is Copyright © 2015 by Matthias Urlichs <matthias@urlichs.de>,
##  it is licensed under the GPLv3. See the file `README.rst` for details,
##  including optimistic statements by the author.
##
##  This program is free software: you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation, either version 3 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License (included; see the file LICENSE)
##  for more details.
##
##  This header is auto-generated and may self-destruct at any time,
##  courtesy of "make update". The original is in ‘scripts/_boilerplate.py’.
##  Thus, do not remove the next line, or insert any blank lines above.
##
import logging
logger = logging.getLogger(__name__)
##BP
import asyncio
loop = asyncio.get_event_loop()

from aio_etcd.client import Client
import sys
from pprint import pprint

from optparse import OptionParser
parser = OptionParser(conflict_handler="resolve")
parser.add_option("-h","--help","-?", action="help",
    help="print this help text")
parser.add_option("-s", "--server", dest="host", action="store",
    default="127.0.0.1", help="etcd server to connect to")
parser.add_option("-p", "--port", dest="port", action="store",
    default=None, type=int, help="User to connect as")
parser.add_option("-d", "--dump", dest="dump", action="store_true",
    help="show internal data")
parser.add_option("-r", "--root", dest="root", action="store",
    default='/', help="Subtree to dump")

(opts, args) = parser.parse_args()

if args:
	print("I do not recognize non-option arguments.", file=sys.stderr)
	sys.exit(1)

args = {'host':opts.host}
if opts.port:
	args['port']=opts.port
et = Client(**args)

async def callback(r):
	if opts.dump:
		pprint(r.__dict__)
	elif r.dir:
		print(r.action,r.key[len(opts.root):])
	elif r.action not in {'compareAndDelete','delete','expire'} and hasattr(r,'value'):
		print(r.action,r.key[len(opts.root):],r.value)
	else:
		print(r.action,r.key[len(opts.root):],r._prev_node.value)
loop.run_until_complete(et.eternal_watch(opts.root, callback=callback,recursive=True))

