package net.northking.cctp.scriptcase.tools.iosPng;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class PNGTrunk {
    protected int m_nSize;
    protected String m_szName;
    protected byte[] m_nData;
    protected byte[] m_nCRC;


    public static PNGTrunk generateTrunk(DataInputStream input) throws IOException {
        int nSize = readPngInt(input);

        byte[] nData = new byte[4];
        input.readFully(nData);
        String szName = new String(nData, "ASCII");

        byte[] nDataBuffer = new byte[nSize];
        input.readFully(nDataBuffer);

        byte[] nCRC = new byte[4];
        input.readFully(nCRC);

        if (szName.equalsIgnoreCase("IHDR")) {
            return new PNGIHDRTrunk(nSize, szName, nDataBuffer, nCRC);
        }

        return new PNGTrunk(nSize, szName, nDataBuffer, nCRC);
    }

    protected PNGTrunk(int nSize, String szName, byte[] nCRC) {
        m_nSize = nSize;
        m_szName = szName;
        m_nCRC = nCRC;
    }

    protected PNGTrunk(int nSize, String szName, byte[] nData, byte[] nCRC) {
        this(nSize, szName, nCRC);
        m_nData = nData;
    }

    public int getSize() {
        return m_nSize;
    }

    public String getName() {
        return m_szName;
    }

    public byte[] getData() {
        return m_nData;
    }

    public byte[] getCRC() {
        return m_nCRC;
    }

    public void writeToStream(OutputStream outStream) throws IOException {
        byte nSize[] = new byte[4];
        nSize[0] = (byte) ((m_nSize & 0xFF000000) >> 24);
        nSize[1] = (byte) ((m_nSize & 0xFF0000) >> 16);
        nSize[2] = (byte) ((m_nSize & 0xFF00) >> 8);
        nSize[3] = (byte) (m_nSize & 0xFF);

        outStream.write(nSize);
        outStream.write(m_szName.getBytes("ASCII"));
        outStream.write(m_nData, 0, m_nSize);
        outStream.write(m_nCRC);
    }

    public static int readPngInt(DataInputStream input) throws IOException {
        final byte[] buffer = new byte[4];
        input.readFully(buffer);
        return readInt(buffer, 0);
    }

    public static int readInt(byte[] nDest, int nPos) { //读一个int
        return ((nDest[nPos++] & 0xFF) << 24)
                | ((nDest[nPos++] & 0xFF) << 16)
                | ((nDest[nPos++] & 0xFF) << 8)
                | (nDest[nPos] & 0xFF);
    }

}
