#!/usr/bin/env python3

cmd_desc = "Run one iteration of the idle show.  Communicates with the hardware servers via OSC packets."

import argparse
import time
import math
import logging
import threading
import signal

import numpy as np

# import the pythonosc package
from pythonosc import osc_message_builder
from pythonosc import udp_client

# OSC port for lighting commands
import stage.config

# import common logging functions
import stage.logconfig

# initialize logging for this module
log = logging.getLogger('idle')

#================================================================
# build an RGBA animation spline

off     = np.array((0,0,0,0))
blue    = np.array((0,0,255,0))
purple  = np.array((255,0,255,0))

rgba1_spline = np.vstack((off, blue, blue,
                          blue, off, off,
                          off, purple, purple,
                          purple, off, off,
                          off, blue, blue,
                          blue, purple, purple,
                          purple, blue, blue,
                          blue, off, off))

rgba2_spline = np.vstack((off, off, off,
                          off, blue, blue,
                          blue, off, off,
                          off, purple, purple,
                          purple, off, off,
                          off, blue, blue,
                          blue, purple, purple,
                          purple, blue, blue,
                          blue, off, off))

#================================================================
# The following section is run when this is loaded as a script.
if __name__ == "__main__":

    # set up logging
    stage.logconfig.open_log_file('logs/idle-show.log')
    log.info("Starting idle-show.py")
    np.set_printoptions(linewidth=np.inf)

    # Initialize the command parser.
    parser = argparse.ArgumentParser(description = cmd_desc)
    parser.add_argument("--ip", default=stage.config.theater_IP,  help="IP address of the OSC receiver (default: %(default)s).")
    stage.logconfig.add_logging_args(parser)

    # Parse the command line, returning a Namespace.
    args = parser.parse_args()

    # Modify logging settings as per common arguments.
    stage.logconfig.configure_logging(args)

    # Create the lighting port.
    lights = udp_client.SimpleUDPClient(args.ip, stage.config.lighting_UDP_port)

    # Issue the sequence.
    msg1 = ['rgba1'] + [int(x) for x in rgba1_spline.flatten()]
    lights.send_message('/spline', msg1)

    msg2 = ['rgba2'] + [int(x) for x in rgba2_spline.flatten()]
    lights.send_message('/spline', msg2)

    # Wait while the sequence runs.
    try:
        segments = len(rgba1_spline) // 3
        time.sleep(1.0 + 1.0 * segments)

    except KeyboardInterrupt:
        log.info("User interrupted operation.")
        print("User interrupt, shutting down.")

    log.info("Exiting idle-show.py")
