/*
 * 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.config.ejb;

import com.queplix.core.integrator.entity.EntityViewHelper;
import com.queplix.core.jxb.entity.Entity;
import com.queplix.core.modules.config.error.UnknownEntityException;
import com.queplix.core.modules.config.utils.ConfigPropertyFactory;
import com.queplix.core.utils.cache.Cache;
import com.queplix.core.utils.ejb.AbstractSessionEJB;

import java.util.Collection;
import java.util.Iterator;

/**
 * <p>LogonSession EJB drives the Entity EntityViewConfig EJBs</p>
 *
 * @author [ALB] Baranov Andrey
 * @version $Revision: 1.1.1.1 $ $Date: 2005/09/12 15:30:14 $
 */

public class EntityViewConfigManagerEJB
        extends AbstractSessionEJB {

    //---------------------------------------------------------------- public methods

    /**
     * Initialize bean
     */
    public void ejbCreate() {
    }

    /**
     * Delete all Entity objects from database.
     *
     * @return number of updated records
     */
    public int deleteEntities() {

        long time = System.currentTimeMillis();
        DEBUG("Try to delete all entity view configs");

        // Clear cache
        Cache cache = ConfigPropertyFactory.getInstance()
                .getEntityViewConfigCache();
        cache.clear();

        EntityViewHelper.getInstance().clearCache();

        // Delete all records.
        int updated = ConfigPropertyFactory.getInstance()
                .getEntityViewConfigDAO().clearAllEntityVO();

        if(getLogger().isDebugEnabled()) {
            DEBUG("Delete all entity configs - ok. Count " + updated +
                    ". Time (ms): " + (System.currentTimeMillis() - time));
        }

        return updated;
    }

    /**
     * Delete Entity object from database.
     *
     * @param entityName entity name attribute
     * @return number of updated records
     */
    public int deleteEntityViewConfig(String entityName) {

        if(getLogger().isDebugEnabled()) {
            DEBUG("Try to delete entity view config '" + entityName + "'");
        }

        // Clear cache
        Cache cache = ConfigPropertyFactory.getInstance()
                .getEntityViewConfigCache();
        cache.clear();

        EntityViewHelper.getInstance().clearCache();

        // Delete one record.
        int updated = ConfigPropertyFactory.getInstance()
                .getEntityViewConfigDAO().clearEntityVO(entityName);

        return updated;
    }

    /**
     * Get Entity value object by the name
     *
     * @param entityName entity name attribute
     * @return Entity object
     */
    public Entity getEntityViewConfig(String entityName) {

        if(getLogger().isDebugEnabled()) {
            DEBUG("Try to get entity view config '" + entityName + "'");
        }

        // Try to find out in cache.
        Cache cache = ConfigPropertyFactory.getInstance()
                .getEntityViewConfigCache();
        Entity entity = (Entity) cache.get(entityName);

        if(entity == null) {
            // Load record from database.
            entity = ConfigPropertyFactory.getInstance()
                    .getEntityViewConfigDAO().loadEntityVO(entityName);

            // Store in cache.
            cache.put(entityName, entity);

        } else {
            // Found in cache!
            if(getLogger().isDebugEnabled()) {
                DEBUG("Entity '" + entityName + "' found in the cache.");
            }
        }

        if(entity == null) {
            throw new UnknownEntityException(entityName,
                    "Incorrect entity class format. " +
                            "Please call entity tool again.");
        }

        // Return read-only entity.
        return entity;
    }

    /**
     * Get collection of Entity value objects
     *
     * @return collection of Entity objects
     */
    public Collection getEntityViewConfigs() {

        Collection entities;
        long time = System.currentTimeMillis();

        DEBUG("Try to get All entities");

        Cache cache = ConfigPropertyFactory.getInstance()
                .getEntityViewConfigCache();
        if(cache.isOpen()) {
            // Load entities.
            entities = ConfigPropertyFactory.getInstance()
                    .getEntityViewConfigDAO().loadAllEntityVO();

            synchronized(cache) {
                // Clear cache.
                cache.clear();

                EntityViewHelper.getInstance().clearCache();

                // Store entities in cache.
                if(entities != null) {
                    for(Iterator it = entities.iterator(); it.hasNext();) {
                        Entity entity = (Entity) it.next();
                        cache.put(entity.getName(), entity);
                    }
                }

                // Close cache.
                cache.close();
            }

        } else {
            // Take entire cache.
            entities = cache.values();
        }

        if(getLogger().isDebugEnabled()) {
            DEBUG("Get All entitiy view configs - ok. Time (ms): " + (
                    System.currentTimeMillis() - time));
        }

        // Return read-only collection.
        return entities;
    }

    /**
     * Create new Entity object
     *
     * @param entity Entity object
     * @return count of updated records
     */
    public int createEntityViewConfig(Entity entity) {

        String entityName = entity.getName();

        if(getLogger().isDebugEnabled()) {
            DEBUG("Try to create entity view config '" + entityName + "'");
        }

        // Clear cache.
        Cache cache = ConfigPropertyFactory.getInstance()
                .getEntityViewConfigCache();
        cache.clear();

        EntityViewHelper.getInstance().clearCache();

        // Update History object.
        ConfigPropertyFactory.getInstance().getEntityViewConfigDAO()
                .storeHistoryVO(entity);

        // Create Entity object.
        return ConfigPropertyFactory.getInstance().getEntityViewConfigDAO()
                .storeEntityVO(entity);
    }

    /**
     * Fill collection of Entity objects
     *
     * @param entities collection of Entity objects
     * @return number of updated records
     */
    public int fillEntityViewConfigs(Entity[] entities) {

        long time = System.currentTimeMillis();
        INFO("Try to fill All Entity objects");

        // Delete all first.
        deleteEntities();

        // Create new again.
        int updated = 0;
        int count = entities.length;
        for(int i = 0; i < count; i++) {
            Entity entity = entities[i];
            String name = entity.getName();
            updated += createEntityViewConfig(entity);

            if(getLogger().isInfoEnabled()) {
                INFO((i + 1) + "[" + count + "] deploy entity '" + name
                        + "' - ok");
            }
        }

        if(getLogger().isDebugEnabled()) {
            INFO("Fill all entity configs - ok. Count " + count +
                    ". Time (ms): " + (System.currentTimeMillis() - time));
        }

        return updated;
    }
}
