#include <psemek/ui/color_view.hpp>
#include <psemek/log/log.hpp>

namespace psemek::ui
{

	math::interval<float> color_view::width_constraints(float height) const
	{
		if (square_)
			return {height, height};
		return element::width_constraints(height);
	}

	math::interval<float> color_view::height_constraints(float width) const
	{
		if (square_)
			return {width, width};
		return element::height_constraints(width);
	}

	void color_view::draw(painter & p) const
	{
		math::box<float, 2> box = shape_.box;
		if (square_)
		{
			if (box[0].length() > box[1].length())
				box[0] = math::expand(math::interval<float>::singleton(box[0].center()), box[1].length() / 2.f);
			else
				box[1] = math::expand(math::interval<float>::singleton(box[1].center()), box[0].length() / 2.f);
		}

		if (color_[3] != 255)
		{
			p.draw_rect(box, {255, 255, 255, 255});

			int const n = 4;
			math::vector<float, 2> d = box.dimensions() / (n * 1.f);

			for (int x = 0; x < n; ++x)
			{
				for (int y = 0; y < n; ++y)
				{
					if ((x + y) % 2 == 0) continue;

					auto origin = box.corner(0.f, 0.f) + math::pointwise_mult(d, {x * 1.f, y});

					p.draw_rect(math::span(origin, origin + d), {191, 191, 191, 255});
				}
			}
		}

		if (color_[3] != 0)
			p.draw_rect(box, color_);
	}

}
