#!/usr/bin/env python3
# *****************************************************************************
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Module authors:
#   Alexander Zaft <a.zaft@fz-juelich.de>
#
# *****************************************************************************

"""SEC node autodiscovery tool."""

import argparse
import sys
from pathlib import Path
# Add import path for inplace usage
sys.path.append(str(Path(__file__).absolute().parents[1]))
from frappy.protocol.discovery import scan, listen


def print_answer(answer, *, short=False):
    if short:
        # NOTE: keep this easily parseable!
        print(f'{answer.equipment_id} {answer.hostname}:{answer.port}')
        return
    numeric = f' ({answer.address})' if answer.address == answer.hostname else ''
    print(f'Found {answer.equipment_id} at {answer.hostname}{numeric}:')
    print(f'  Port: {answer.port}')
    print(f'  Firmware: {answer.firmware}')
    desc = answer.description.replace('\n', '\n    ')
    print(f'  Node description: {desc}')
    print('-' * 80)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--listen', action='store_true',
                        help='Keep listening after the broadcast.')
    parser.add_argument('-s', '--short', action='store_true',
                        help='Print short info (always on when listen).')
    args = parser.parse_args(sys.argv[1:])
    short = args.listen or args.short
    if not short:
        print('-' * 80)
    for answer in scan():
        print_answer(answer, short=short)
    if args.listen:
        for answer in listen():
            print_answer(short=short)
