#!/usr/bin/env python
# In project imports
import srp_md
import srp_md.ui as ui
from srp_md import srp_md_log

# Ros imports
import rospy

# Python imports
import logging
import argparse
import sys
import signal

# Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QTimer

# Get a logger
loger = logging.getLogger('srp_md')


def sigint_handler(*args):
    QApplication.quit()


def parse_args():
    """
    Parse input arguments
    """
    parser = argparse.ArgumentParser(description='Run SRPMD Program')
    parser.add_argument('--gui', dest='gui', help='Specify GUI to use [pyqt | term]',
                        default='pyqt', type=str)
    args = parser.parse_args()
    return args


def main():
    # Get arguments
    args = parse_args()

    # Setup ros
    rospy.init_node('srp_md')

    # Define the srp
    srp = srp_md.SrpMd()

    # Define user interface
    ctrl = ui.Controller(srp)
    view = ui.TermView(srp, ctrl)

    # Run
    if args.gui == 'term':
        r = rospy.Rate(100)
        while not rospy.is_shutdown() and view.running:
            view.run_once()
            r.sleep()
    elif args.gui == 'pyqt':
        signal.signal(signal.SIGINT, sigint_handler)
        app = QApplication([])
        gui = ui.PyQtView(srp, ctrl)
        timer = QTimer()
        timer.start(10)
        timer.timeout.connect(lambda: None)
        app.exec_()


if __name__ == '__main__':
    loger.debug('System starting up... #BOLD')
    sys.argv = rospy.myargv()
    try:
        main()
    finally:
        loger.debug('System shuting down... #BOLD')
