package org.jivesoftware.smack.util;

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

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

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

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

   public LazyStringBuilder append(CharSequence csq) {
      assert csq != null;

      this.list.add(csq);
      this.invalidateCache();
      return this;
   }

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

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

   public int length() {
      if (this.cache != null) {
         return this.cache.length();
      } else {
         int length = 0;

         CharSequence csq;
         for(Iterator i$ = this.list.iterator(); i$.hasNext(); length += csq.length()) {
            csq = (CharSequence)i$.next();
         }

         return length;
      }
   }

   public char charAt(int index) {
      if (this.cache != null) {
         return this.cache.charAt(index);
      } else {
         CharSequence csq;
         for(Iterator i$ = this.list.iterator(); i$.hasNext(); index -= csq.length()) {
            csq = (CharSequence)i$.next();
            if (index < csq.length()) {
               return csq.charAt(index);
            }
         }

         throw new IndexOutOfBoundsException();
      }
   }

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

   public String toString() {
      if (this.cache == null) {
         StringBuilder sb = new StringBuilder(this.length());
         Iterator i$ = this.list.iterator();

         while(i$.hasNext()) {
            CharSequence csq = (CharSequence)i$.next();
            sb.append(csq);
         }

         this.cache = sb.toString();
      }

      return this.cache;
   }
}
