/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (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.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.core;

import com.arsdigita.util.Assert;
import com.arsdigita.util.UncheckedWrapperException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import org.apache.log4j.Logger;

/**
 * Subject to change.
 *
 * @author Justin Ross &lt;jross@redhat.com&gt;
 * @version $Id: //core-platform/dev/src/com/arsdigita/core/MessageMap.java#3 $
 */
final class MessageMap {
    public static final String versionId =
        "$Id: //core-platform/dev/src/com/arsdigita/core/MessageMap.java#3 $" +
        "$Author: dennis $" +
        "$DateTime: 2004/04/07 16:07:11 $";

    private static final Logger s_log = Logger.getLogger(MessageMap.class);

    private final HashMap m_messages;

    public MessageMap() {
        m_messages = new HashMap();
    }

    public String get(final String key) {
        Assert.exists(key, String.class);

        return (String) m_messages.get(key);
    }

    public void load(final Reader reader) {
        try {
            internalLoad(reader);
        } catch (IOException ioe) {
            throw new UncheckedWrapperException(ioe);
        }
    }

    private void internalLoad(final Reader reader) throws IOException {
        Assert.exists(reader, Reader.class);

        final BufferedReader breader = new BufferedReader(reader);

        String line = null;
        String key = null;
        StringBuffer message = new StringBuffer();

        while ((line = breader.readLine()) != null) {
            if (line.startsWith("[") && line.endsWith("]")) {
                if (key != null) {
                    m_messages.put(key, message.toString().trim());
                }

                message = new StringBuffer();

                key = line.substring(1, line.length() - 1);

                continue;
            }

            message.append(line + "\n");
        }

        m_messages.put(key, message.toString().trim());
    }
}
