#!/usr/bin/python
# Copyright (c) 2010 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 """

    """
    return

def main(argv):

    def callback(uuid, source, target, data):
        schedule = data.get('schedule', None)
        if (schedule is not None):
            if (len(schedule) > 0):
                for entry in schedule:
                    uuid, route_id, context_id, input_data, schedule_type, schedule = entry
                    route = ctx.run_command('route::get', id=route_id)
                    if (input_data is None):
                        route_name = '{0} with no input'.format(route.name)
                    else:
                        route_name = '{0} with input'.format(route.name)
                    account = ctx.run_command('contact::get', id=context_id)
                    login = account.login
                    if (schedule_type == 'date'):
                        print '{0}: {1} as {2} at {3}'.\
                            format(uuid, route_name, login, schedule.strftime('%Y-%m-%d %H:%M'))
                    elif (schedule_type == 'interval'):
                        weeks, days, hours, minutes, seconds, start, count = schedule
                        description = '{0} weeks {1} days {2} hours {3} minutes'.format(weeks, days, hours, minutes)
                        print '{0}: {1} as {2} every {3} starting at {4} for {5} iterations'.\
                            format(uuid,
                                   route_name,
                                   login,
                                   description,
                                   start.strftime('%Y-%m-%d %H:%M'),
                                   count)
                    elif schedule_type == 'crontab':
                        year, month, day, weekday, hour, minute = schedule
                        description = 'year=\'{0}\' month=\'{1}\' day=\'{2}\' weekday=\'{3}\' hour=\'{4}\' minute=\'{5}\''.\
                                        format(year, month, day, weekday, hour, minute)
                        print '{0}: {1} as {2} for pattern {3}'.\
                            format(uuid, route_name, login, description)
            else:
                print 'No scheduled jobs.'
        else:
            print 'No schedule available.'
        return True

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

    ctx.run_command('process::get-schedule', callback=callback, all_jobs=True)
    ctx.wait()
    ctx.close()

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