/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.xwork2;

import java.util.ResourceBundle;

import com.opensymphony.xwork2.LocaleProvider;
import com.opensymphony.xwork2.ResourceBundleTextProvider;
import com.opensymphony.xwork2.inject.Inject;

/**
 * This factory enables users to provide and correctly initialize a custom TextProvider.
 */
public class TextProviderFactory {

    private TextProvider textProvider;

    /**
     * @param textProvider textProvider
     */
    @Inject
    public void setTextProvider(TextProvider textProvider) {
        this.textProvider = textProvider;
    }

    protected TextProvider getTextProvider() {
        if (this.textProvider == null) {
			return new TextProviderSupport();
		}
		else {
			return textProvider;
		}
    }

    /**
     * @param clazz class 
     * @param provider locale provider
     * @return text provider
     */
    public TextProvider createInstance(Class clazz, LocaleProvider provider) {
        TextProvider instance = getTextProvider();
        if (instance instanceof ResourceBundleTextProvider) {
            ((ResourceBundleTextProvider) instance).setClazz(clazz);
            ((ResourceBundleTextProvider) instance).setLocaleProvider(provider);
        }
        return instance;
    }

    /**
     * @param bundle resource bundle
     * @param provider locale provider
     * @return text provider
     */
    public TextProvider createInstance(ResourceBundle bundle, LocaleProvider provider) {
        TextProvider instance = getTextProvider();
        if (instance instanceof ResourceBundleTextProvider) {
            ((ResourceBundleTextProvider) instance).setBundle(bundle);
            ((ResourceBundleTextProvider) instance).setLocaleProvider(provider);
        }
        return instance;
    }
}
