/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (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.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * 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 com.queplix.core.modules.eqlext.actions;

import com.queplix.core.error.GenericSystemException;
import com.queplix.core.integrator.security.LogonSession;
import com.queplix.core.modules.eql.error.EQLException;
import com.queplix.core.modules.eqlext.ejb.ReportManagerLocal;
import com.queplix.core.modules.eqlext.ejb.ReportManagerLocalHome;
import com.queplix.core.modules.eqlext.utils.ReportHelper;
import com.queplix.core.modules.jeo.JEObjectHandler;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocal;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocalHome;
import com.queplix.core.modules.jeo.gen.ReportSchedulerObject;
import com.queplix.core.modules.jeo.gen.ReportSchedulerObjectHandler;
import com.queplix.core.modules.services.XAAction;
import com.queplix.core.utils.DateHelper;
import com.queplix.core.utils.JNDINames;
import com.queplix.core.utils.cache.CacheObjectManager;

import javax.mail.MessagingException;
import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Sends scheduled reports by mail.
 *
 * @author [ONZ] Oleg N. Zhovtanyuk
 * @version $Revision: 1.2 $ $Date: 2006/08/24 16:21:58 $
 */
public class SendReportsAction
        extends XAAction {

    // ========================================================== Action handler

    /* (non-Javadoc)
     * @see Action#perform
     */

    public Serializable perform() {

        long time = System.currentTimeMillis();
        INFO("Sending scheduled reports...");

        // Initialization.
        CacheObjectManager com = getContext().getCOM();
        JEOManagerLocal jeoManager = (JEOManagerLocal) com.getLocalObject(
                JNDINames.JEOManager, JEOManagerLocalHome.class);
        ReportManagerLocal reportManager = (ReportManagerLocal) com
                .getLocalObject(JNDINames.ReportManager,
                        ReportManagerLocalHome.class);
        LogonSession ls = getContext().getLogonSession();

        try {

            // Get the reports, scheduled to send by now.
            List hnds = ReportSchedulerObjectHandler.selectScheduledReports(
                    jeoManager, ls);
            if(hnds == null || hnds.isEmpty()) {
                INFO("No scheduled reports to send.");
                return null;
            }

            // Process reports.
            Date now = DateHelper.getNowDate();
            for(Iterator it = hnds.iterator(); it.hasNext();) {

                JEObjectHandler hnd = (JEObjectHandler) it.next();
                ReportSchedulerObject obj = (ReportSchedulerObject) hnd
                        .getJEObject();

                long reportScheduleID = obj.getReport_sched_id().longValue();
                int period = obj.getPeriod().intValue();
                int periodUnit = obj.getPeriod_unit().intValue();
                Date lastSend = obj.getNext_date();
                DEBUG("Sending report by schedule ID = " + reportScheduleID);

                // Skip any one-time schedule, that was already sent.
                if(periodUnit == ReportHelper.ONE_TIME
                        && lastSend.getTime() < 0) {
                    DEBUG("One-time schedule, and was already sent - skipped.");
                    continue;
                }

                // 	Send the report by schedule ID.
                //  extacting this part to separate method allows redefining from
                //  Project specific action methods (for sending formatted report)
                sendReportByScheduleId(reportManager, reportScheduleID, obj);

                // Reschedule the report for the future.
                Date nextSend = ReportHelper.reschedule(period, periodUnit,
                        lastSend, now);
                obj.setNext_date(nextSend);
                DEBUG("Report is sent and re-scheduled to " + nextSend);
                hnd.commit();
            }

        } catch (EQLException ex) {
            ERROR(ex);
            throw new GenericSystemException(ex);
        }

        // Ok.
        INFO("Completed, time = " + (System.currentTimeMillis() - time)
                + " ms.");
        return null;

    }

    protected void sendReportByScheduleId(ReportManagerLocal reportManager,
                                          long reportScheduleID,
                                          ReportSchedulerObject obj)
            throws EQLException {
        try {
            reportManager.sendReportByMail(reportScheduleID);
        } catch (MessagingException me) {
            ERROR(me);
        }
    }
}
