#!/usr/bin/python3
import argparse
import signal
from typing import Sequence

from mpire.dashboard import start_dashboard


def get_port_range() -> Sequence:
    """
    :return: port range
    """
    def _port_range(range_str) -> Sequence:
        n1, n2 = map(int, range_str.split('-'))
        if len(range(n1, n2)) < 2:
            raise ValueError
        return range(n1, n2)

    parser = argparse.ArgumentParser(description='MPIRE Dashboard')
    parser.add_argument('--port-range', dest='port_range', required=False, default=range(8080, 8100), type=_port_range,
                        help='Port range for starting a dashboard. The range should accommodate at least two ports: '
                             'one for the webserver and one for the Python Manager server. Example: 6060-6080 will be '
                             'converted to `range(6060, 6080)`. Default: `range(8080, 8100)`.')
    return parser.parse_args().port_range


if __name__ == '__main__':
    # Obtain port range
    port_range = get_port_range()

    # Start a dashboard
    print("Starting MPIRE dashboard...")
    dashboard_details = start_dashboard(port_range)

    # Print some details on how to connect
    print()
    print("MPIRE dashboard started on http://localhost:{}".format(dashboard_details['dashboard_port_nr']))
    print("Server is listening on {}:{}".format(dashboard_details['manager_host'],
                                                dashboard_details['manager_port_nr']))
    print("-" * 50)
    signal.pause()
