/* FichothequeLib_API - Copyright (c) 2006-2020 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.fichotheque.corpus.fiche;

import java.io.Serializable;
import java.util.AbstractList;
import java.util.RandomAccess;


/**
 *
 * @author Vincent Calame
 */
public class Ul extends AbstractList<Li> implements FicheBlock, RandomAccess, Serializable {

    private static final long serialVersionUID = 7L;
    private Li[] liArray = new Li[4];
    private int size;
    private AttsImpl attsImpl;

    /**
     * Contient toujours au moins un élément li
     */
    public Ul(Li li) {
        if (li == null) {
            throw new IllegalArgumentException("li is null");
        }
        liArray[0] = li;
        size = 1;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Li get(int index) {
        if (index >= size) {
            throw new IndexOutOfBoundsException();
        }
        return liArray[index];
    }

    @Override
    public boolean add(Li li) {
        if (li == null) {
            throw new NullPointerException();
        }
        checkLength();
        liArray[size] = li;
        size++;
        return true;
    }

    private void checkLength() {
        if (size == liArray.length) {
            Li[] nv = new Li[size * 2];
            System.arraycopy(liArray, 0, nv, 0, size);
            liArray = nv;
        }
    }

    @Override
    public Atts getAtts() {
        return AttsImpl.check(attsImpl);
    }

    @Override
    public void putAtt(String name, String value) {
        String mode = null;
        if (name.equals("class")) {
            mode = check(value, "OL", "ol");
            if (mode == null) {
                mode = check(value, "DL", "dl");
            }
        }
        if (mode != null) {
            attsImpl = AttsImpl.put(attsImpl, "mode", mode);
        } else {
            attsImpl = AttsImpl.put(attsImpl, name, value);
        }
    }

    private String check(String value, String prefix, String mode) {
        if (!value.startsWith(prefix)) {
            return null;
        }
        int length = prefix.length();
        if (value.length() > length) {
            attsImpl = AttsImpl.put(attsImpl, "class", value.substring(length + 1));
        }
        return mode;
    }

}
