/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.text.format;

import net.ranides.assira.text.StringUtils;

/**
 *
 * @author ranides
 */
public class AnsiBuilder extends AnsiString {
    
    private static final long serialVersionUID = 3L;
    
    private int position;
    
    public AnsiBuilder() {
        this(16);
    }
    
    public AnsiBuilder(int capacity) {
        super(capacity);
        position = 0;
    }
    
    public AnsiBuilder append(AnsiCharSequence seq) {
        int count = seq.length();
        checkCapacityFor(count);
        for(int i=0; i<count; i++) {
            text[position] = seq.charAt(i);
            backList[position] = (byte)seq.getBackAt(i);
            foreList[position] = (byte)seq.getForeAt(i);
            flagList[position] = (char)seq.getFlagsAt(i);
            fontList[position] = (byte)seq.getFontAt(i);
            position++;
        }
        return this;
    }
    
    public AnsiBuilder append(CharSequence seq, AnsiAttr attributes) {
        int count = seq.length();
        checkCapacityFor(count);
        
        setAttr(position, position+count, attributes);
        replace(position, seq);
        position += count;
        return this;
    }
    
    public AnsiBuilder append(int count, char ch, AnsiAttr attributes) {
        checkCapacityFor(count);
        
        setAttr(position, position+count, attributes);
        replace(position, StringUtils.repeat(count, ch));
        position += count;
        return this;
    }

    protected void checkCapacityFor(int count) {
        int capacity = position + count;
        if(capacity >= text.length ) {
            
            char[] newText = new char[capacity];
            byte[] newForeList = new byte[capacity];
            byte[] newBackList = new byte[capacity];
            char[] newFlagList = new char[capacity];
            byte[] newFontList = new byte[capacity];
            
            System.arraycopy(text, 0, newText, 0, text.length);
            System.arraycopy(foreList, 0, newForeList, 0, foreList.length);
            System.arraycopy(backList, 0, newBackList, 0, backList.length);
            System.arraycopy(flagList, 0, newFlagList, 0, flagList.length);
            System.arraycopy(fontList, 0, newFontList, 0, fontList.length);
            
            text = newText;
            foreList = newForeList;
            backList = newBackList;
            flagList = newFlagList;
            fontList = newFontList;
        }

    }
    
    public AnsiString result() {
        AnsiString ret = new AnsiString(text, backList, foreList, flagList, fontList, position);
        ret.setScheme(scheme);
        return ret;
    }
}
