#include <png.h>
#include <log.h>
#include "raw.h"

namespace render{

rawImage::rawImage()
{
    this->pixeles = nullptr;
}

rawImage::rawImage(const std::string &path):rawImage()
{
    this->load(path);
}

rawImage::~rawImage()
{
    this->free();
}

bool rawImage::load(const std::string &path, bool flip)
{
    this->free();

    unsigned char header[8];
    FILE *texFile = fopen(path.c_str(), "rb");

    if (!texFile) {
        return false;
    }

    fread(header, 1, 8, texFile);

    png_sig_cmp(header, 0, 8);

    png_structp img = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);

    png_infop img_info = png_create_info_struct(img);

    setjmp(png_jmpbuf(img));

    png_init_io(img, texFile);
    png_set_sig_bytes(img, 8);

    png_read_info(img, img_info);

    long width = png_get_image_width(img, img_info);
    long height = png_get_image_height(img, img_info);
    int color = png_get_color_type(img, img_info);

    this->size.x = width;
    this->size.y = height;

    switch (color) {
    case PNG_COLOR_TYPE_RGB:
        this->pixelSize = 3;
        break;
    case PNG_COLOR_TYPE_RGBA:
        this->pixelSize = 4;
        break;
    default:
        break;
        // i dunno
    }

    this->pixeles = new uint8_t[width * height * this->pixelSize];

    for(int i = 0; i < height; i++) {
        png_read_row(img, (png_bytep)(this->pixeles + i * width * this->pixelSize), nullptr);
    }

    png_destroy_read_struct(&img, &img_info, nullptr);

    fclose(texFile);

	return true;
}

void rawImage::free()
{
    if (this->pixeles) {
        delete [] this->pixeles;
        this->pixeles = nullptr;
    }
}

}
