#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <sstream>
#include <iomanip>

#include "text.h"
#include "histogram.h"
#include "histogram_internal.h"


using namespace std;

std::string getRandomHexColor() {
	random_device rd;  // Источник случайных чисел
	mt19937 gen(rd()); // Генератор Mersenne Twister
	std::uniform_int_distribution<> dis(0, 255); // Равномерное распределение [0, 255]

	int r = dis(gen); // Красный
	int g = dis(gen); // Зеленый
	int b = dis(gen); // Синий

	// Формируем HEX-строку
	std::stringstream hexStream;
	hexStream << "#"
		<< std::hex << std::setw(2) << std::setfill('0') << r
		<< std::hex << std::setw(2) << std::setfill('0') << g
		<< std::hex << std::setw(2) << std::setfill('0') << b;

	return hexStream.str();
}

void
svg_begin(double width, double height) {
	cout << "<?xml version='1.0' encoding='UTF-8'?>\n";
	cout << "<svg ";
	cout << "width='" << width << "' ";
	cout << "height='" << height << "' ";
	cout << "viewBox='0 0 " << width << " " << height << "' ";
	cout << "xmlns='http://www.w3.org/2000/svg'>\n";
}

void
svg_end() {
	cout << "</svg>\n";
}

void
svg_text(double left, double baseline, string text) {
	cout << "<text x='" << left << "' y='" << baseline << "'>" << text << "</text>" << endl;
}

void svg_rect(double x, double y, double width, double height, string stroke = "black", string fill = "black") {
	cout << "<rect x='" << x << "' y='" << y << "' width='" << width << "' height='" << height << "' stroke='" << stroke << "' fill='" << fill << "' />" << endl;
}

void
show_histogram_svg(const vector<size_t> bins) {

	auto mm = *(max_element(bins.begin(), bins.end()));
	const auto IMAGE_WIDTH = 400;
	const auto IMAGE_HEIGHT = 300;
	const auto TEXT_LEFT = 20;
	const auto TEXT_BASELINE = 20;
	const auto TEXT_WIDTH = 50;
	const auto BIN_HEIGHT = 30;
	const auto PROCENT_SPACE = 50;
	auto BLOCK_WIDTH = 10;
	auto sum_bins = 0;

	BLOCK_WIDTH = (IMAGE_WIDTH - TEXT_WIDTH) / mm;

	svg_begin(600, 400);

	for (size_t Elem : bins) {
		sum_bins += Elem;
	}

	double top = 0;
	for (size_t bin : bins) {
		const double bin_width = BLOCK_WIDTH * bin;
		double PROCENT = double(bin) / double(sum_bins);
		PROCENT = round(PROCENT * 100) / 100 ;
		svg_text(TEXT_LEFT, top + TEXT_BASELINE, to_string(bin));

		svg_rect(TEXT_WIDTH, top, bin_width, BIN_HEIGHT, "grey", getRandomHexColor());

		svg_text(IMAGE_WIDTH + PROCENT_SPACE, top + TEXT_BASELINE, to_string(int(PROCENT * 100)) + "%");
		top += BIN_HEIGHT;

	}



	//svg_begin(400, 300);
	//svg_text(20, 35, to_string(bins[0]));
	//svg_rect(50, 0, bins[0] * 10, 30, "purple", "red");
	svg_end();

}



