#include <array>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <png.h>

std::vector<png_byte> make_png() {
    png_image image{};
    image.version = PNG_IMAGE_VERSION;
    image.width = 3;
    image.height = 1;
    image.format = PNG_FORMAT_RGBA;
    const std::array<png_byte, 12> pixels{
        0, 0, 0, 0,   0, 0, 0, 128,   0, 0, 0, 255
    };

    png_alloc_size_t size = 0;
    if (!png_image_write_to_memory(&image, nullptr, &size, 0, pixels.data(), 0, nullptr))
        throw std::runtime_error(image.message);
    std::vector<png_byte> encoded(size);
    if (!png_image_write_to_memory(&image, encoded.data(), &size, 0, pixels.data(), 0, nullptr))
        throw std::runtime_error(image.message);
    encoded.resize(size);
    return encoded;
}

void print_composite(const std::vector<png_byte>& encoded, const char* label,
                     const png_color& backdrop) {
    png_image image{};
    image.version = PNG_IMAGE_VERSION;
    if (!png_image_begin_read_from_memory(&image, encoded.data(), encoded.size()))
        throw std::runtime_error(image.message);

    image.format = PNG_FORMAT_RGB;
    std::array<png_byte, 9> rgb{};
    if (!png_image_finish_read(&image, &backdrop, rgb.data(), 0, nullptr))
        throw std::runtime_error(image.message);

    std::cout << label;
    for (std::size_t i = 0; i < rgb.size(); i += 3)
        std::cout << " (" << +rgb[i] << ',' << +rgb[i + 1] << ',' << +rgb[i + 2] << ')';
    std::cout << '\n';
}

int main() {
    try {
        const auto encoded = make_png();
        std::cout << "libpng " << png_get_libpng_ver(nullptr) << '\n';
        std::cout << "black foreground, alpha: 0 128 255\n";
        print_composite(encoded, "white backdrop:", {255, 255, 255});
        print_composite(encoded, "black backdrop:", {0, 0, 0});
    } catch (const std::exception& error) {
        std::cerr << error.what() << '\n';
        return 1;
    }
}
