#ifndef GASPARDOS_FRAMEBUFFER_HPP
#define GASPARDOS_FRAMEBUFFER_HPP
#include <stdint.h>
#include <algorithm>
#include <cstdlib>
#include <vector>

namespace gaspardos
{
    // Owned software pixels, portable to host tests. RGBX = 0x00BBGGRR.
    class Framebuffer
    {
        unsigned              width_, height_;
        std::vector<uint32_t> pixels_;

    public:
        Framebuffer(unsigned width, unsigned height) : width_(0), height_(0)
        {
            resize(width, height);
        }

        bool resize(unsigned width, unsigned height)
        {
            if (!width || !height || width > 1024 || height > 1024)
                return false;
            std::vector<uint32_t> replacement(static_cast<std::size_t>(width) * height, 0);
            pixels_.swap(replacement);
            width_  = width;
            height_ = height;
            return true;
        }

        unsigned width() const
        {
            return width_;
        }

        unsigned height() const
        {
            return height_;
        }

        uint32_t* pixels()
        {
            return pixels_.empty() ? 0 : &pixels_[0];
        }

        const uint32_t* pixels() const
        {
            return pixels_.empty() ? 0 : &pixels_[0];
        }

        void clear(uint32_t color)
        {
            std::fill(pixels_.begin(), pixels_.end(), color);
        }

        void pixel(int x, int y, uint32_t color)
        {
            if (x >= 0 && y >= 0 && static_cast<unsigned>(x) < width_
                && static_cast<unsigned>(y) < height_)
                pixels_[static_cast<std::size_t>(y) * width_ + x] = color;
        }

        uint32_t pixel(int x, int y) const
        {
            return x >= 0 && y >= 0 && static_cast<unsigned>(x) < width_
                           && static_cast<unsigned>(y) < height_
                       ? pixels_[static_cast<std::size_t>(y) * width_ + x]
                       : 0;
        }

        void circle(int x, int y, unsigned radius, uint32_t color)
        {
            if (radius > 1024 || x < -2048 || x > 2048 || y < -2048 || y > 2048)
                return;
            int dx = static_cast<int>(radius), dy = 0, error = 1 - dx;
            while (dx >= dy)
            {
                pixel(x + dx, y + dy, color);
                pixel(x + dy, y + dx, color);
                pixel(x - dy, y + dx, color);
                pixel(x - dx, y + dy, color);
                pixel(x - dx, y - dy, color);
                pixel(x - dy, y - dx, color);
                pixel(x + dy, y - dx, color);
                pixel(x + dx, y - dy, color);
                ++dy;
                if (error < 0)
                    error += 2 * dy + 1;
                else
                {
                    --dx;
                    error += 2 * (dy - dx) + 1;
                }
            }
        }
    };
}  // namespace gaspardos
#endif
