/**
 * JBoss, Home of Professional Open Source
 * Copyright 2008, Red Hat Middleware LLC, and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.webbeans.ticker;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.context.ApplicationScoped;
import javax.event.Observes;
import javax.inject.Current;
import javax.inject.manager.Manager;
import org.jboss.webbeans.environment.se.events.Shutdown;
import org.jboss.webbeans.environment.se.events.Start;
import org.jboss.webbeans.log.Log;
import org.jboss.webbeans.log.Logging;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

/**
 * Fires up a new thread and ticks every second (pproximately).
 * @author Peter Royle
 */
@ApplicationScoped
public class TimeKeeperStarter
{
    @Current Manager manager;
    public static final String MANAGER_NAME = "manager";

    private static final String JOB_GROUP = "ticker_job_group";
    Scheduler scheduler;
    Log log = Logging.getLog( TimeKeeperStarter.class );

    public void startTicker( @Observes Start start )
    {
        try
        {
            scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.start();

            JobDetail job = new JobDetail( "ticker", JOB_GROUP, Ticker.class );
            job.setJobDataMap( new JobDataMap());
            job.getJobDataMap().put(  MANAGER_NAME, manager);
            Trigger trigger = new SimpleTrigger( "trigger1", JOB_GROUP, new Date() );
            scheduler.scheduleJob( job, trigger );

        } catch (SchedulerException ex)
        {
            Logger.getLogger( TimeKeeperStarter.class.getName() ).log( Level.SEVERE, null, ex );
        }


    }

    public void stopTicker( @Observes Shutdown shutdown )
    {
        try
        {
            scheduler.shutdown();
        } catch (SchedulerException ex)
        {
            log.error( "Error shutting down scheduler", ex );
        }
    }
}
