goog.provide('FlappBitmap');
goog.require('FlappIBit');
goog.require('FlappString');

goog.scope(function() {

/**
 * @constructor
 */
FlappBitmap = function() {
    ;
};

FlappBitmap.jpegChunkOffsets = function(jpegData) {
    var offsetTable = {};
    var ibit = new FlappIBit();
    ibit.inputArray(jpegData);
    while (ibit.hasNext(2)) {
        var offset = ibit.getBytePos();
        var marker = ibit.ui16be();
        var length;
        switch (marker) {
        case 0xFFD8: // SOI
        case 0xFFD9: // EOI
            break;
        case 0xFFDA: // SOS + [RST] + EOI
            length = ibit.len() - offset;
            offsetTable[marker] = [[offset, length]];
            break;
        default:
            length = 2 + ibit.ui16be();;
            ibit.seek(length - 4, 0);
            if (marker in offsetTable) {
                offsetTable[marker].push([offset, length]);
            } else {
                offsetTable[marker] = [[offset, length]];
            }
            break;
        }
    }
    return offsetTable;
};

FlappBitmap.toJpeg = function(swfJpeg, jpegTables) {
    var offsetTable = FlappBitmap.jpegChunkOffsets(swfJpeg);
    var hasDQT = (0xFFDB in offsetTable);
    if (hasDQT === false) {
        if (jpegTables === null) {
            console.error("swfJpeg has no DQT and jpegTables is null.");
            return ""; // TODO: return dummy small image
        }
        var offsetTable2 = FlappBitmap.jpegChunkOffsets(jpegTables);
    }
    var jpegArray = [0xFF, 0xD8]; // SOI
    // APP0, SOF0, DQT, DHT, SOS
    var jpegOrder = [0xFFE0, 0xFFC0, 0xFFDB, 0xFFC4, 0xFFDA];
    for (var i = 0, l = jpegOrder.length; i < l ; i++) {
        var marker = jpegOrder[i];
        var table, jpeg;
        if (marker in offsetTable) {
            table = offsetTable;
            jpeg = swfJpeg;
        } else {
            table = offsetTable2;
            jpeg = jpegTables;
        }
        var chunkOffsets = table[marker];
        for (var j = 0, jl= chunkOffsets.length; j < jl ; j++) {
            var offset = chunkOffsets[j][0];
            var endoffset = offset + chunkOffsets[j][1];
            for (var k = offset; k < endoffset ; k++) {
                jpegArray.push(jpeg[k]);
            }
        }
    }
    return FlappString.ArrayToString(jpegArray);
};

FlappBitmap.toPng = function(lossless) {
    ;
};

});
