#!/usr/bin/env python3.6
"""Start Kytos SDN Platform core."""
import daemon
import IPython
import signal

from IPython.terminal.embed import InteractiveShellEmbed
from IPython.terminal.prompts import Prompts, Token

from kytos.core import Controller
from kytos.core.config import KytosConfig

from traitlets.config.loader import Config

class KytosPrompt(Prompts):
     def in_prompt_tokens(self, cli=None):
         return [(Token.Prompt, 'kytos $> ')]

controller = None
kill_handler = None

banner1 = """\033[95m
  _          _
 | |        | |
 | | ___   _| |_ ___  ___
 | |/ / | | | __/ _ \/ __|
 |   <| |_| | || (_) \__ \\
 |_|\_\\\\__, |\__\___/|___/
        __/ |
       |___/
\033[0m
Welcome to Kytos SDN Platform!

We are doing a huge effort to make sure that this console will work fine. But
for now is still experimental.

Kytos website.: https://kytos.io/
Documentation.: https://docs.kytos.io/
OF Address....:"""

exit_msg = "Stopping Kytos daemon... Bye, see you!"

def stop_controller(signum, frame):
    """Stop the controller before quitting."""
    if controller:
        print('Stopping controller...')
        # If stop() hangs, old ctrl+c behaviour will be restored
        signal.signal(signal.SIGINT, kill_handler)
        controller.stop()


kill_handler = signal.signal(signal.SIGINT, stop_controller)

if __name__ == '__main__':
    config = KytosConfig()
    controller = Controller(config.options['daemon'])
    if controller.options.foreground:
        controller.start()
        address = controller.server.server_address[0]
        port = controller.server.server_address[1]
        banner1 += " tcp://{}:{}\n".format(address, port)
        banner1 += "WEB UI........: http://0.0.0.0:8181/"

        cfg = Config()
        cfg.TerminalInteractiveShell.autocall = 2
        cfg.TerminalInteractiveShell.show_rewritten_input = False

        ipshell = InteractiveShellEmbed(config=cfg,
                                        banner1=banner1,
                                        exit_msg=exit_msg)
        ipshell.prompts = KytosPrompt(ipshell)
        ipshell()
        controller.stop()
    else:
        with daemon.DaemonContext():
            controller.start()
        print('Kytos daemon started.')
