OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Blame | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.utils.text;

import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.text.DateTimeFormat.Literal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

public final class DateTimeFormatBuilder {

    static public final DateTimeFormat build(final Object... components) {
        final DateTimeFormatBuilder res = new DateTimeFormatBuilder(components.length);
        for (final Object o : components) {
            if (o instanceof DateTimeFormatComponent)
                res.add((DateTimeFormatComponent) o);
            else
                res.addLiteral(o.toString());
        }
        return res.build();
    }

    static public final DateTimeSkeleton buildSkeleton(final DateProp... components) {
        return new DateTimeSkeleton(CollectionUtils.toImmutableList(components));
    }

    private final List<DateTimeFormatComponent> components;
    private boolean onlyDateProp = true;

    public DateTimeFormatBuilder() {
        this(8);
    }

    public DateTimeFormatBuilder(int initialCapacity) {
        super();
        this.components = new ArrayList<>(initialCapacity);
    }

    public final boolean isEmpty() {
        return this.components.isEmpty();
    }

    public final void clear() {
        this.components.clear();
        this.onlyDateProp = true;
    }

    public final DateTimeFormatBuilder add(DateTimeFormatComponent comp) {
        this.components.add(comp);
        return this;
    }

    public final DateTimeFormatBuilder addLiteral(final String s) {
        this.components.add(new Literal(s));
        this.onlyDateProp = false;
        return this;
    }

    public final DateTimeFormat build() {
        return new DateTimeFormat(this.components);
    }

    public final DateTimeSkeleton buildSkeleton() {
        if (!this.onlyDateProp)
            throw new IllegalStateException("Not only DateProp");
        return new DateTimeSkeleton(Collections.unmodifiableList(CollectionUtils.castList(Objects.requireNonNull(this.components), DateProp.class)));
    }
}