/*
 * 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.services.update.impl;

import com.queplix.core.integrator.security.LogonSession;
import com.queplix.core.modules.eql.EQLResCell;
import com.queplix.core.modules.eql.error.EQLException;
import com.queplix.core.modules.eql.error.EQLSystemException;
import com.queplix.core.modules.eql.update.EntityUpdate;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocal;
import com.queplix.core.modules.jeo.ejb.JEOManagerLocalHome;
import com.queplix.core.modules.jeo.gen.ScriptParametersObject;
import com.queplix.core.modules.jeo.gen.ScriptParametersObjectHandler;
import com.queplix.core.modules.jeo.gen.TaskObject;
import com.queplix.core.modules.jeo.gen.TaskObjectHandler;
import com.queplix.core.modules.jeo.gen.TaskParametersObject;
import com.queplix.core.modules.jeo.gen.TaskParametersObjectHandler;
import com.queplix.core.modules.services.ejb.ScriptManager;
import com.queplix.core.modules.services.ejb.ScriptManagerHome;
import com.queplix.core.utils.JNDINames;

import java.util.List;

/**
 * Task update.
 *
 * @author [ALB] Baranov Andrey
 * @version $Revision: 1.2 $ $Date: 2005/10/21 14:13:30 $
 */

public class TaskUpdate
        extends EntityUpdate {

    /* (non-Javadoc)
     * @see EntityUpdate#afterUpdate()
     */
    public int beforeUpdate()
            throws EQLException {

        long time = System.currentTimeMillis();
        INFO("Task before update started...");

        // Initialization.
        TaskObjectHandler taskHnd = (TaskObjectHandler) getJEOHandler(
                TaskObjectHandler.class);
        TaskObject taskObject = (TaskObject) taskHnd.getJEObject();

        // Check task parameters
        boolean repeat = (taskObject.getRepeat() != null) && (
                taskObject.getRepeat().intValue() == 1);
        if(repeat) {
            if(taskObject.getDelay() == null) {
                throwUserQueryParseException("delay", null);
            }
            if(taskObject.getDelay().intValue() <= 0) {
                throwUserQueryParseException("delay",
                        "" + taskObject.getDelay());
            }
            if(taskObject.getTask_delayunit_id() == null) {
                throwUserQueryParseException("task_delayunit_id", null);
            }
        }

        // Ok.
        INFO("Before update completed, time = "
                + (System.currentTimeMillis() - time) + " ms.");
        return CONTINUE;
    }

    /* (non-Javadoc)
     * @see EntityUpdate#afterUpdate()
     */
    public void afterUpdate()
            throws EQLException {

        if(isNew()) {
            //
            // Initialize task parameters
            //
            // Initialization.
            TaskObjectHandler taskHnd = (TaskObjectHandler) getJEOHandler(
                    TaskObjectHandler.class);
            TaskObject taskObject = (TaskObject) taskHnd.getJEObject();

            // Get task and script IDs
            long task_id = taskObject.getTask_id().longValue();
            int script_id = taskObject.getScript_id().intValue();
            JEOManagerLocal jeoManager = (JEOManagerLocal) getCOM()
                    .getLocalObject(JNDINames.JEOManager,
                            JEOManagerLocalHome.class);
            LogonSession ls = getEUO().getSession().getLogonSession();

            // Get script parameters by script ID
            List scriptParamsHndList = ScriptParametersObjectHandler
                    .selectByScriptId(jeoManager, ls, script_id);
            int size = (scriptParamsHndList == null) ? 0
                    :scriptParamsHndList.size();

            DEBUG("Try to copy " + size + " script parameters...");

            for(int i = 0; i < size; i++) {
                ScriptParametersObjectHandler scriptParamHnd
                        = (ScriptParametersObjectHandler)
                        scriptParamsHndList.get(i);
                ScriptParametersObject scriptParamObject
                        = (ScriptParametersObject) scriptParamHnd.getJEObject();

                // Create new task parameter
                TaskParametersObjectHandler taskParamHnd
                        = (TaskParametersObjectHandler)
                        jeoManager.create(ls,
                                TaskParametersObjectHandler.class);
                TaskParametersObject taskParamObject
                        = (TaskParametersObject) taskParamHnd.getJEObject();

                // Set task ID
                taskParamObject.setTask_id(new Long(task_id));

                // Copy script parameter attributes
                taskParamObject.setScript_param_id(
                        scriptParamObject.getScript_param_id());
                taskParamObject.setValue(scriptParamObject.getDef_value());

                // Commit
                taskParamHnd.commit();
            }
        }

        removeFromCache();
    }


    /* (non-Javadoc)
     * @see EntityUpdate#afterDelete()
     */
    public void afterDelete() {
        removeFromCache();
    }

    /**
     * Removes current record from the cache.
     */
    protected void removeFromCache() {

        if(isNew()) {
            return;
        }

        EQLResCell idCell = getCell("task_id");
        Long id = idCell.getLong();
        ScriptManager scriptManager = (ScriptManager) getCOM().getRemoteObject(
                JNDINames.ScriptManagerRemote, ScriptManagerHome.class);

        // Flushes Cache.
        try {
            scriptManager.flushTaskCache(id.longValue());
        } catch (java.rmi.RemoteException ex) {
            ERROR(ex);
            throw new EQLSystemException(ex.getCause());
        }

    }
}
