/*
 * Decompiled with CFR 0.152.
 */
package org.jivesoftware.smack.util;

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

public class LazyStringBuilder
implements Appendable,
CharSequence {
    private final List<CharSequence> list = new ArrayList<CharSequence>(20);
    private String cache;

    private void invalidateCache() {
        this.cache = null;
    }

    public LazyStringBuilder append(LazyStringBuilder lsb) {
        this.list.addAll(lsb.list);
        this.invalidateCache();
        return this;
    }

    @Override
    public LazyStringBuilder append(CharSequence csq) {
        assert (csq != null);
        this.list.add(csq);
        this.invalidateCache();
        return this;
    }

    @Override
    public LazyStringBuilder append(CharSequence csq, int start, int end) {
        CharSequence subsequence = csq.subSequence(start, end);
        this.list.add(subsequence);
        this.invalidateCache();
        return this;
    }

    @Override
    public LazyStringBuilder append(char c) {
        this.list.add(Character.toString(c));
        this.invalidateCache();
        return this;
    }

    @Override
    public int length() {
        if (this.cache != null) {
            return this.cache.length();
        }
        int length = 0;
        for (CharSequence csq : this.list) {
            length += csq.length();
        }
        return length;
    }

    @Override
    public char charAt(int index) {
        if (this.cache != null) {
            return this.cache.charAt(index);
        }
        for (CharSequence csq : this.list) {
            if (index < csq.length()) {
                return csq.charAt(index);
            }
            index -= csq.length();
        }
        throw new IndexOutOfBoundsException();
    }

    @Override
    public CharSequence subSequence(int start, int end) {
        return this.toString().subSequence(start, end);
    }

    @Override
    public String toString() {
        if (this.cache == null) {
            StringBuilder sb = new StringBuilder(this.length());
            for (CharSequence csq : this.list) {
                sb.append(csq);
            }
            this.cache = sb.toString();
        }
        return this.cache;
    }
}
