#!/usr/bin/python2.6
# Copyright (c) 2010, 2012 Adam Tauno Williams <awilliam@whitemice.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#

# TODO: Add usage information

from coils.core  import *
import getopt, sys, os

def usage():
    print """
    List the server's workflow schedule
    """
    return

def main(argv):

    try:
        ctx, params = initialize_tool('list-schedule', argv)
    except getopt.GetoptError, e:
        print 'unable to initialize OpenGroupware Coils subsystem'
        print e
        sys.exit(2)

    schedule = ctx.run_command('workflow::get-schedule')
    
    for job in schedule:
        
        route_id = job['routeId']
        route_name = 'n/a'
        if route_id:
            route = ctx.run_command('route::get', id=route_id)
            if route:
                route_name = route.name
            
        context_id = job['contextId']
        login_name = 'n/a'
        if context_id:
            context = ctx.run_command('contact::get', id = context_id)
            if context:
                login_name = context.login
            
        if job['attachmentUUID']:
            attachment_id = job['attachmentUUID'].split('@')[0]
        else:
            attachment_id = 'n/a'
            
        print(' Schedule Entry UUID:{0}\n' \
              '   Attachment: {1}\n' \
              '   contextId#{2}  "{3}"\n' \
              '   routeId#{4} "{5}"\n'\
              '   Iterations - Performed: {6}  Remaining: {7}\n'
              '   Extended Attributes:'.format( job['UUID'], 
                                                  attachment_id,
                                                  job['contextId'], login_name,
                                                  job['routeId'], route_name,
                                                  job['iterationsPerformed'],
                                                  job['iterationsRemaining'] ) )
        for key, value in job['xattrDict'].items():
            print('     Key: {0}  Value: "{1}"'.format( key, value ))
        print('   Schedule: {0}'.format(job['type']))
        if job['type'] == 'cron':
            print('     year: "{0}" month: "{1}" day: "{2}" dayOfWeek: "{3}" hour: "{4}" minute: "{5}"'.
                format( job['year'], job['month'], job['day'], 
                        job['dayOfWeek'], job['hour'], job['minute'] ))
        elif job['type'] == 'interval':
            print('     every {0} seconds starting @ {1}'.format(job['interval'], job['start']))
        else:
            print('     @ {0}'.format(job['date']))

if __name__ == "__main__":
    main(sys.argv[1:])
