/*
 * Copyright (C) 2001-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.globalization;

import java.util.Locale;

/**
 * <p>
 * Represents one of possibly many of the values of the Accept-Language HTTP
 * headers.
 * </p>
 *
 * @version $Revision: #7 $ $Date: 2004/04/07 $
 */
public class AcceptLanguage extends AcceptField {
    public final static String versionId = "$Id: //core-platform/dev/src/com/arsdigita/globalization/AcceptLanguage.java#7 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";

    private String m_language = "";
    private Locale m_locale = null;

    /**
     * <p>
     * Constructor.
     * </p>
     *
     * @param acceptLanguage String representing one entry from the
     *        Accept-Language HTTP headers. This can look like: "en" or "en;
     *        q=0.75" or "*"
     */
    public AcceptLanguage(String acceptLanguage) {
        if (acceptLanguage == null) {
            throw new NullPointerException("acceptLanguage cannot be null");
        }

        int semi = acceptLanguage.indexOf(';');

        if (semi == -1) {
            setLanguage(acceptLanguage);
            setQValue(DEFAULT_Q_VALUE);
        } else {
            setLanguage(acceptLanguage.substring(0, semi));
            setQValue(acceptLanguage.substring(semi + 1));
        }

        setLocale();
    }

    public final String getLanguage() {
        return m_language;
    }

    private void setLanguage(String language) {
        Locale dl = Locale.getDefault();

        language = language.trim();

        if (language.equals("*")) {
            m_language =
                dl.getCountry() == null || dl.getCountry().length() == 0 ?
                dl.getLanguage() :
                dl.getLanguage() + "-" + dl.getCountry();
        } else {
            m_language = language;
        }
    }

    public final Locale getLocale() {
        return m_locale;
    }

    private void setLocale() {
        int dash = m_language.indexOf('-');

        if (dash == -1) {
            // no country provided
            m_locale = new Locale(m_language, "");
        } else {
            m_locale = new Locale(
                                  m_language.substring(0, dash),
                                  m_language.substring(dash + 1)
                                  );
        }
    }
}
