#!/usr/local/bin/python3.6
# You may redistribute this program 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 for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import cjdns
from cjdns import key_utils
import argparse
try:
    from prettytable import PrettyTable
except ImportError:
    import sys
    sys.stderr.write("""This utility requires prettytable, please install it.
    You can do:
        $ pip install prettytable
    or go download it from https://code.google.com/p/prettytable/\n""")
    sys.exit()

parser = argparse.ArgumentParser(description='Display stats about your peers.')
parser.add_argument('--pubkeys', '-p', dest='pubkeys', action='store_true',
                    help="Don't convert public keys into IP addresses")
parser.add_argument('--ips', '-i', dest='pubkeys', action='store_false',
                    help="Convert public keys into IP addresses")
parser.set_defaults(pubkeys=False)
args = parser.parse_args()

firstcolheader = 'Public Key'
if not args.pubkeys:
    firstcolheader = 'cjdns IP'

connection = cjdns.connectWithAdminInfo()
table = PrettyTable([
    firstcolheader,
    'state',
    'user',
    'Bytes In',
    'Bytes Out',
    'Switch Label',
    'Duplicates',
    'Received Out Of Range',
    'Last',
    'Version',
    'Is Incoming'])

i = 0
more = True
while more:
    page = connection.InterfaceController_peerStats(i)
    for peer in page['peers']:
        user = "-"
        if "user" in peer:
            user = peer['user']
        key = peer['publicKey']
        if not args.pubkeys:
            key = key_utils.to_ipv6(peer['publicKey'])
        table.add_row([
            key,
            peer['state'],
            user,
            peer['bytesIn'],
            peer['bytesOut'],
            peer['switchLabel'],
            peer['duplicates'],
            peer['receivedOutOfRange'],
            peer['last'],
            peer['version'],
            peer['isIncoming']
            ])
    i += 1
    more = 'more' in page

print(table)
