package jp.sourceforge.nicoro.swf;

import static jp.sourceforge.nicoro.swf.Log.DEBUG_LOGD;
import static jp.sourceforge.nicoro.swf.Log.LOG_TAG;
import jp.sourceforge.nicoro.FailAnalyzeSwfException;

public class LINESTYLEARRAY {
	public short lineStyleCount;		// UI8
	public int lineStyleCountExtended;		// UI16
	public LINESTYLE[] lineStyles;
	public LINESTYLE2[] lineStyles2;

    public int read(byte[] bufferArray, int offset, int tagType) throws FailAnalyzeSwfException {
    	LINESTYLEARRAY lineStyleArray = this;

		if (DEBUG_LOGD) {
			Log.d(LOG_TAG, Log.buf().append("readLINESTYLEARRAY: offset=")
					.append(offset).toString());
		}

    	int lineStyleCount;
    	int offsetLineStyles;
    	lineStyleArray.lineStyleCount = (short) (bufferArray[offset] & 0xff);
    	if (DEBUG_LOGD) {
    		Log.d(LOG_TAG, Log.buf().append("LineStyleCount=")
    				.append(lineStyleArray.lineStyleCount).toString());
    	}
    	if (lineStyleArray.lineStyleCount == 0xff) {
    		lineStyleArray.lineStyleCountExtended =
    			((bufferArray[offset + 1] & 0xff) | ((bufferArray[offset + 2] & 0xff) << 8));
        	if (DEBUG_LOGD) {
        		Log.d(LOG_TAG, Log.buf().append("LineStyleCountExtended=")
        				.append(lineStyleArray.lineStyleCountExtended).toString());
        	}
    		lineStyleCount = lineStyleArray.lineStyleCountExtended;
    		offsetLineStyles = offset + 1 + 2;
    	} else {
    		lineStyleCount = lineStyleArray.lineStyleCount;
    		offsetLineStyles = offset + 1;
    	}

		switch (tagType) {
		case RECORDHEADER.SWFTAG_DEFINESHAPE:
		case RECORDHEADER.SWFTAG_DEFINESHAPE2:
		case RECORDHEADER.SWFTAG_DEFINESHAPE3:
	    	lineStyleArray.lineStyles = new LINESTYLE[lineStyleCount];
	    	for (int i = 0; i < lineStyleCount; ++i) {
	    		LINESTYLE lineStyle = new LINESTYLE();
	    		offsetLineStyles = lineStyle.read(bufferArray, offsetLineStyles, tagType);
	    		lineStyleArray.lineStyles[i] = lineStyle;
	    	}
	    	break;
		case RECORDHEADER.SWFTAG_DEFINESHAPE4:
			// TODO
	    	lineStyleArray.lineStyles2 = new LINESTYLE2[lineStyleCount];
	    	for (int i = 0; i < lineStyleCount; ++i) {
	    		LINESTYLE2 lineStyle2 = new LINESTYLE2();
	    		offsetLineStyles = lineStyle2.read(bufferArray, offsetLineStyles, tagType);
	    		lineStyleArray.lineStyles2[i] = lineStyle2;
	    	}
	    	break;
		default:
			Log.w(LOG_TAG, Log.buf().append("LINESTYLEARRAY: record tag type mismatch=")
					.append(tagType).toString());
			break;
		}

    	return offsetLineStyles;
    }

}
