package gov.nasa.worldwind.formats.nitfs;

import gov.nasa.worldwind.formats.rpf.*;
/*
Copyright (C) 2001, 2007 United States Government
as represented by the Administrator of the
National Aeronautics and Space Administration.
All Rights Reserved.
*/

/**
 * @author Lado Garakanidze
 * @version $Id: CompressionLookupRecord Apr 17, 2007 3:29:33 PM lado
 */
class CompressionLookupRecord
{
    public int getTableID()
    {
        return this.tableID;
    }

    public int getNumOfRecords()
    {
        return this.numOfRecords;
    }

    public int getNumOfValuesPerRecord()
    {
        return this.numOfValuesPerRecord;
    }

    public int getValueBitLength()
    {
        return this.valueBitLength;
    }

    public short getBytesPerRecord()
    {
        return this.bytesPerRecord;
    }

    public byte[] copyValues(byte [] dest, int destOffset, int idx, int len)
    {
        if(len != this.bytesPerRecord)
            throw new NitfsRuntimeException("NitfsReader.AttemptToCopyWithInvalidSizeOfRecord");
        if(idx  >= this.numOfRecords)
            throw new NitfsRuntimeException("NitfsReader.AttemptToCopyOutOfBoundsAtSource");
        if(null == dest)
            throw new NitfsRuntimeException("NitfsReader.AttemptCopyToIvalidDestination");
        if(dest.length < destOffset + len)
            throw new NitfsRuntimeException("NitfsReader.AttemptToCopyOutOfBoundsAtDestination");

        System.arraycopy(lut, idx * this.bytesPerRecord, dest, destOffset, this.bytesPerRecord);

        return dest;
    }


    private int     tableID;
    private int     numOfRecords;
    private int     numOfValuesPerRecord;
    private int     valueBitLength;
    private int     tableLocation;
    private short   bytesPerRecord;

    private byte[]  lut;

    public CompressionLookupRecord(java.nio.ByteBuffer buffer,
        int compressionLookupSubsectionLocation,
        RpfColorMap[] colormaps // TODO update LUT with the color mapped values to gain performance
    )

    {
        this.tableID = NitfsUtil.getUShort(buffer);
        this.numOfRecords = (int) NitfsUtil.getUInt(buffer);
        this.numOfValuesPerRecord = NitfsUtil.getUShort(buffer);
        this.valueBitLength = NitfsUtil.getUShort(buffer);
        this.tableLocation = (int) (NitfsUtil.getUInt(buffer) + compressionLookupSubsectionLocation);
        int saveOffset = buffer.position();

        this.bytesPerRecord = (short) (this.numOfValuesPerRecord * this.valueBitLength/8L);
        this.lut = new byte[ this.numOfRecords * this.bytesPerRecord ];

        buffer.position(this.tableLocation);
        buffer.get(this.lut, 0, this.numOfRecords * this.bytesPerRecord);

        buffer.position(saveOffset);
    }
}
