#!/usr/bin/python
import argparse
import logging
import logging.handlers

from config import Config
from cam import Cam


### Arguments
arg_parser = argparse.ArgumentParser(description='flashair uploader')
# check if cams are online, if yes download all new pictures and upload them to the remote server
arg_parser.add_argument('--sync', help="synchronise pictures from the cams to the ftp server", action='store_true')

arguments = vars(arg_parser.parse_args())


### logger
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT)
log = logging.getLogger(__name__)
# Also log output to syslog
handler = logging.handlers.SysLogHandler(address = '/dev/log')
fmt = 'flashair-uploader[%(process)-5s:%(thread)d]: ' \
                '%(levelname)-5s %(message)s'
handler.setFormatter(logging.Formatter(fmt=fmt))
log.addHandler(handler)

### Main function
def main(arguments):
    """
    Gets the parsed arguments and loads the configurations.
    If the arguments was "--sync" the sync procedure starts

    Input: parsed arguments
    Output: NULL
    """
    # load the configuration
    log.debug("loading configuration")
    config = Config(arguments)
    config.load()
    log.info("configuration loaded")

    # Set the defined log level
    try:
        log.setLevel(config.conf['DEFAULT']['log_level'])
    except ValueError:
        log.error("The configured LogLevel is wrong " + config.conf['DEFAULT']['log_level'])

    log.debug("LogLevel: " + config.conf['DEFAULT']['log_level'])

    # Do a sync if correct arguments are passed
    if arguments['sync']:
        log.debug("syncing pictures from cams")
        sync(config)



def sync(config):
    """
    Starts the sync procedure for all cameras if and only if they are online

    Input: config object
    Output: NULL
    """
    # Loads all cams
    cams = config.conf.sections()
    # Iterate through the cams
    for cam_i in cams:
        log.debug("initialize cam object for " + cam_i)
        # Creates a Cam object for each cam
        cam = Cam(log, cam_i, config.conf[cam_i]['ip'], config.conf[cam_i]['location'], config.conf.defaults())
        try:
            files = cam.getFileList()
            cam.organiseMissing(files)
        except AssertionError:
            log.error(cam_i + " at IP: " + cam.ip + " is offline")



# Start with the main function
main(arguments)