001/**
002 *
003 * Copyright 2020 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.xdata;
018
019import java.util.ArrayList;
020import java.util.Collection;
021import java.util.Date;
022import java.util.List;
023
024import org.jivesoftware.smack.util.CollectionUtil;
025
026import org.jxmpp.util.XmppDateTime;
027
028public class AbstractMultiFormField extends FormField {
029
030    private final List<String> values;
031
032    protected AbstractMultiFormField(Builder<?, ?> builder) {
033        super(builder);
034        values = CollectionUtil.cloneAndSeal(builder.values);
035    }
036
037    @Override
038    public final List<String> getValues() {
039        return values;
040    }
041
042
043    public abstract static class Builder<F extends FormField, B extends FormField.Builder<F, B>>
044                    extends FormField.Builder<F, B> {
045
046        private List<String> values;
047
048        protected Builder(AbstractMultiFormField formField) {
049            super(formField);
050            values = CollectionUtil.newListWith(formField.getValues());
051        }
052
053        protected Builder(String fieldName, FormField.Type type) {
054            super(fieldName, type);
055        }
056
057        private void ensureValuesAreInitialized() {
058            if (values == null) {
059                values = new ArrayList<>();
060            }
061        }
062
063        @Override
064        protected void resetInternal() {
065            values = null;
066        }
067
068        public abstract B addValue(CharSequence value);
069
070        public B addValueVerbatim(CharSequence value) {
071            ensureValuesAreInitialized();
072
073            values.add(value.toString());
074            return getThis();
075        }
076
077        public final B addValue(Date date) {
078            String dateString = XmppDateTime.formatXEP0082Date(date);
079            return addValueVerbatim(dateString);
080        }
081
082        public final B addValues(Collection<? extends CharSequence> values) {
083            ensureValuesAreInitialized();
084
085            for (CharSequence value : values) {
086                this.values.add(value.toString());
087            }
088
089            return getThis();
090        }
091    }
092}