/*
 * 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.client.frames.mainframe.impl;

import com.queplix.core.client.app.vo.FamgMeta;
import com.queplix.core.client.common.AbstractCachingFactory;
import com.queplix.core.client.frames.mainframe.BusinessOperationStrategy;
import com.queplix.core.client.frames.mainframe.DefaultOperationStrategy;
import com.queplix.core.client.frames.mainframe.OperationContext;
import com.queplix.core.client.frames.mainframe.StrategiesFactory;

/**
 * Builds default strategies. Implement singleton interface. Use caching,
 * so be careful of using old operation context.
 * <p/>
 * Implement singleton interface for strategies coupling purpose.
 *
 * @author Sergey Kozmin
 * @since 11.04.2007
 */
public class DefaultStrategiesFactory extends AbstractCachingFactory
        implements StrategiesFactory {
    private OperationContext opContext;
    private BusinessOperationStrategy defStrategy;

    public DefaultStrategiesFactory(OperationContext opContextIn,
                                    BusinessOperationStrategy defStrategy) {
        this.defStrategy = defStrategy;
        opContext = opContextIn;
    }

    public DefaultStrategiesFactory(OperationContext opContextIn) {
        this(opContextIn, new DefaultOperationStrategy());
    }

    public BusinessOperationStrategy createStrategy(String formId) {
        BusinessOperationStrategy strategy
                = (BusinessOperationStrategy) getObject(
                formId);
        if(strategy == null) {
            initStrategy(defStrategy, formId);
            strategy = defStrategy;
        }
        return strategy;
    }

    private void initStrategy(BusinessOperationStrategy str, String formId) {
        FamgMeta.Index formIndex = (FamgMeta.Index) getOperationContext()
                .getMetaData().getIndexByID(formId);
        str.init(getOperationContext(), formId, formIndex);
    }

    protected Object createObject(String key) {
        return null;
    }

    protected void initObject(String key, Object obj) {
        if(obj != null) {
            BusinessOperationStrategy strategy
                    = (BusinessOperationStrategy) obj;
            initStrategy(strategy, key);
        }
    }

    protected OperationContext getOperationContext() {
        return opContext;
    }
}
