from pngparser import PngParser, chunktypes, ChunkIHDR
import zlib


def calc_crc(chunk):
    return zlib.crc32(chunk.type + chunk.data).to_bytes(chunktypes.CHUNK_CRC_SIZE, 'big')

parser = PngParser("./test.png")

header = parser.get_header()
header.crc = calc_crc(header)
header = ChunkIHDR(chunktypes.TYPE_IHDR, header.data, header.crc)

print(header)

data_chunks = [chunk  for chunk in parser.get_all() if chunk.type not in  [b"IHDR", b"IEND"]]

data_chunks = data_chunks[:10]

for chunk in data_chunks:
    chunk.crc = calc_crc(chunk)

print([chunk.type for chunk in data_chunks])

end_chunk = parser.get_by_type(chunktypes.TYPE_IEND)
end_chunk[0].crc = calc_crc(end_chunk[0])

chunks = [header] + data_chunks + end_chunk 

png_file = bytes.fromhex("89 50 4E 47 0D 0A 1A 0A".replace(" ", ""))

for chunk in chunks:
    png_file += chunk.to_bytes()

with open("test_cut.png", "wb") as f:
    f.write(png_file)

print(len(data_chunks))
