/*
 * Copyright 2004-2005 The Trix Development Team.
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * 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 org.trix.cuery.sac;

import java.util.ArrayList;
import java.util.List;

import org.trix.cuery.MediaType;

import org.w3c.css.sac.SACMediaList;
import org.w3c.dom.DOMException;
import org.w3c.dom.stylesheets.MediaList;

/**
 * DOCUMENT.
 * 
 * @author <a href="mailto:Teletha.T@gmail.com">Teletha Testarossa</a>
 * @version $ Id: SACMediaListImpl.java,v 1.1 2005/08/11 03:08:18 Teletha Exp $
 */
public class SACMediaListImpl implements SACMediaList, MediaList {

    /** The actual list. */
    private List list = new ArrayList(4);

    /**
     * @see org.w3c.css.sac.SACMediaList#getLength()
     */
    public int getLength() {
        return list.size();
    }

    /**
     * @see org.w3c.css.sac.SACMediaList#item(int)
     */
    public String item(int position) {
        return (String) list.get(position);
    }

    /**
     * @see org.w3c.dom.stylesheets.MediaList#appendMedium(java.lang.String)
     */
    public void appendMedium(String media) throws DOMException {
        if (MediaType.isMediaType(media)) {
            list.add(media);
        }
    }

    /**
     * @see org.w3c.dom.stylesheets.MediaList#deleteMedium(java.lang.String)
     */
    public void deleteMedium(String media) throws DOMException {
        list.remove(media);
    }

    /**
     * @see org.w3c.dom.stylesheets.MediaList#getMediaText()
     */
    public String getMediaText() {
        StringBuffer buffer = new StringBuffer();

        for (int i = 0; i < list.size(); i++) {
            buffer.append(list.get(i));

            if (i != list.size() - 1) {
                buffer.append(", ");
            }
        }
        return buffer.toString();
    }

    /**
     * @see org.w3c.dom.stylesheets.MediaList#setMediaText(java.lang.String)
     */
    public void setMediaText(String mediaText) throws DOMException {
        String[] medias = mediaText.split(",");

        for (int i = 0; i < medias.length; i++) {
            appendMedium(medias[i].trim());
        }
    }

    /**
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return getMediaText();
    }

}
