#include "image.h"
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#include "stb_image.h"

image::image(vec2i size) :
	_borrowed_pointer(false),
	_data(new color[size.size()]),
	_bounds(vec2i::zero, size)
{}

image::image(vec2i size, color* data) :
	_borrowed_pointer(true),
	_data(data),
	_bounds(vec2i::zero, size) 
{}

image::image(std::string path) : _borrowed_pointer(false) {
	int w, h, n;
	auto data = reinterpret_cast<color*>(stbi_load(path.c_str(), &w, &h, &n, 0));
	_data = new color[w * h];
	for(int i = 0; i < w*h; ++i) {
		_data[i] = data[i];
		_data[i] = (data[i] & 0xff000000u) |
			((data[i] & 0x00ff0000u) >> 16) |
			(data[i] & 0x0000ff00u) | 
			((data[i] & 0x000000ffu) << 16);
	}
	stbi_image_free(data);
	_bounds = recti(vec2i::zero, vec2i(w, h));
}

image::image(image const& other) :
	_borrowed_pointer(false),
	_data(new color[other.size().size()]),
	_bounds(other.bounds())
{
	std::memcpy(_data, other._data, size().size() * 4);
}

image::~image() {
	if(!_borrowed_pointer && _data)
		delete[] _data;
}

vec2i const& image::size() const {
	return _bounds.size;
}

recti const& image::bounds() const {
	return _bounds;
}

color* image::raw_pointer() const {
	return _data;
}

color image::get(vec2i pos) const {
	return _data[pos.x + pos.y * _bounds.size.x];
}

void image::clear(color color) {
	std::fill(_data, _data + size().size(), color);
}



