"""Draw a pixel-art rocket from rows of numbers."""
from argparse import ArgumentParser
from pathlib import Path
from struct import pack
from zlib import compress, crc32

ROCKET = [
    '00011000',
    '00111100',
    '00122100',
    '00122100',
    '00111100',
    '01111110',
    '01033010',
    '00033000',
]
PALETTES = {
    'moon': [(11, 26, 27), (153, 235, 202), (242, 252, 243), (255, 176, 108)],
    'sunset': [(39, 18, 37), (255, 167, 140), (255, 231, 171), (246, 104, 133)],
}


def draw(palette):
    pixels = []
    for row in ROCKET:
        colors = []
        for digit in row:
            colors.append(palette[int(digit)])
        pixels.append(colors)
    return pixels


def write_png(path, palette):
    pixels = draw(palette)
    # Multiply each pixel to keep the artwork crisp at a useful display size.
    scale = 32
    rows = [b'\0' + b''.join(bytes(color) * scale for color in row) for row in pixels]

    def chunk(kind, data):
        return pack('>I', len(data)) + kind + data + pack('>I', crc32(kind + data))

    header = pack('>IIBBBBB', len(pixels[0]) * scale, len(pixels) * scale, 8, 2, 0, 0, 0)
    image_data = compress(b''.join(row * scale for row in rows))
    Path(path).write_bytes(b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', header)
                           + chunk(b'IDAT', image_data) + chunk(b'IEND', b''))


if __name__ == '__main__':
    parser = ArgumentParser(description=__doc__)
    parser.add_argument('--palette', choices=PALETTES, default='moon')
    parser.add_argument('--output', default='python-rocket.png')
    args = parser.parse_args()
    write_png(args.output, PALETTES[args.palette])
