#!/usr/bin/env python3

# Workflow manager for Illuminate: Randy Pausch Bridge Light-Up Night 2021
# https://www.cs.cmu.edu/~PauschBridge/Illuminate-2021.html

# This tool performs several tasks:
#
#  1. submissions
#     1. monitoring the database of image submissions
#     2. downloading the unfiltered new image submissions to a local cache
#     3. presenting new submissions in an 'inbox' folder
#
#  2. conversion
#     1. monitoring the 'approved' folder for manually approved images
#     2. converting images to a video clip for the bridge
#     3. preparing a preview video clip
#     4. uploading the approved images and preview videos to Google Drive
#
# All state is kept in the file system itself; this tool can be stopped and
# restarted.  Files can be deleted from the local cache to trigger reprocessing.
#
#================================================================
# Dependencies:
#
# The pbridge modules assume the availability of several third-party libraries.
# For details, please see:
#
#   pbridge/video.py:   OpenCV and numpy libraries
#   pbridge/gdrive.py:  Google Drive API libraries
#
# Several modules require configuration settings to be created in config.py.
# If installing from scratch, please follow the instructions in config-prototype.py.
# 
#================================================================
# Import standard Python modules.
import argparse, os, time, sys, signal, logging

import config
import pbridge.gdrive
import pbridge.convmonitor
import pbridge.submonitor

#================================================================
def configure_logging():
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    console_handler.setFormatter(logging.Formatter('%(levelname)s:%(name)s: %(message)s'))
    logging.getLogger().addHandler(console_handler)

    logging.getLogger().setLevel(logging.DEBUG)
    logging.getLogger('googleapiclient.discovery').setLevel(logging.INFO)
    logging.getLogger('google.auth.transport.requests').setLevel(logging.INFO)
    logging.getLogger('urllib3.connectionpool').setLevel(logging.INFO)

#================================================================
def sigint_handler(signal, frame):
    logging.info("Keyboard interrupt caught, shutting down...")
    sys.exit(0)
            
#================================================================
def main():
    # Configure logging to stream messages to the terminal console.
    configure_logging()
    
    # Attach a handler to the keyboard interrupt (control-C).
    signal.signal(signal.SIGINT, sigint_handler)

    # Connect to the Google Drive API.  This may trigger a browser-based
    # authentication process if the token is not found.
    gdrive = pbridge.gdrive.GDrive(config)
    gdrive.authenticate_and_connect()

    sub_monitor  = pbridge.submonitor.SubmissionMonitor(config, gdrive)
    conv_monitor = pbridge.convmonitor.ConversionMonitor(config, gdrive)

    if sub_monitor.ready and conv_monitor.ready:
        while True:
            sub_monitor.poll()
            time.sleep(8.0)            
            conv_monitor.poll()
            time.sleep(8.0)
    else:
        logging.warning("One or more components not ready to run, quitting.")
        
#================================================================
# Main script follows.  This sequence is executed when the script is initiated from the command line.

if __name__ == "__main__":
    main()
        
