# w.c.s. - web application for online forms
# Copyright (C) 2005-2010  Entr'ouvert
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

import sys

from django.conf import settings

class CronJob(object):
    name = None
    hours = None
    minutes = None
    weekdays = None
    days = None
    function = None

    def __init__(self, function, name=None, hours=None, minutes=None, weekdays=None, days=None, hourly=False):
        self.function = function
        self.name = name
        self.hours = hours
        self.minutes = minutes
        self.weekdays = weekdays
        self.days = days
        if hourly:
            # set minutes to an arbitrary value based on installation, this
            # prevents waking up all jobs at the same time on a server farm.
            self.minutes = [ord(settings.SECRET_KEY[-1]) % 60]

def cron_worker(publisher, now, job_name=None):
    try:
        publisher.set_config()
    except:
        return

    # reindex user and formdata if needed (should only be run once)
    if publisher.is_using_postgresql():
        publisher.reindex_sql()

    for job in publisher.cronjobs:
        if job_name:
            # a specific job name is asked, run it whatever
            # the current time is.
            if job.name != job_name:
                continue
        else:
            if job.days and now[2] not in job.days:
                continue
            if job.weekdays and now[6] not in job.weekdays:
                continue
            if job.hours and not now[3] in job.hours:
                continue
            if job.minutes and not now[4] in job.minutes:
                continue

        class FakeRequest(object):
            language = publisher.get_site_language()

        publisher.install_lang(FakeRequest())
        publisher.substitutions.reset()
        publisher.substitutions.feed(publisher)
        for extra_source in publisher.extra_sources:
            publisher.substitutions.feed(extra_source(publisher, None))
        try:
            job.function(publisher)
        except:
            publisher.notify_of_exception(sys.exc_info(), context='[CRON]')
