/*
 * Copyright (C) 2005 - 2011 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com.
 *
 * Unless you have purchased  a commercial license agreement from Jaspersoft,
 * the following license terms  apply:
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License  as
 * published by the Free Software Foundation, either version 3 of  the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero  General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public  License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.jaspersoft.jasperserver.war.common;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Resolves input control label from resource bundles in the following precedence: report-specific bundles, server-wide
 * bundles.
 *
 * @author Yuriy Plakosh
 */
public class InputControlLabelResolver {
    private static Pattern LABEL_KEY_PATTERN = Pattern.compile("^\\$R\\{(.+)\\}(.*)$");

    /**
     * Resolves the input control label by specified message key.
     *
     * @param key                 the message key.
     * @param reportMessageSource the report message source.
     * @param serverMessageSource the server message source.
     * @return resolved label.
     */
    public static String resolve(String key, MessageSource reportMessageSource, MessageSource serverMessageSource) {
        String label = key;

        Matcher m = LABEL_KEY_PATTERN.matcher(key);
        if (m.matches()) {
            // matches $R{<supermart.store.store_sqft.label>} is Between
            String labelKey = m.group(1);
            // matches $R{supermart.store.store_sqft.label}< is Between>
            String labelPostfix = m.group(2);

            boolean messageFound = false;
            if (reportMessageSource != null) {
                try {
                    label = reportMessageSource.getMessage(labelKey, null, LocaleContextHolder.getLocale());
                    messageFound = true;
                } catch (Exception ex) { /* No message. Ok, not a prob... */ }
            }

            if (serverMessageSource != null && !messageFound) {
                try {
                    label = serverMessageSource.getMessage(labelKey, null, LocaleContextHolder.getLocale());
                } catch (Exception ex) { /* No message. Ok, not a prob... */ }
            }

            label += labelPostfix;
        }

        return label;
    }
}
