#include <iostream>
#include "svg.h"

using namespace std;

const auto IMAGE_WIDTH = 400;
const auto IMAGE_HEIGHT = 310;
const auto TEXT_LEFT = 20;
const auto TEXT_BASELINE = 20;
const auto TEXT_WIDTH = 50;
const auto BIN_HEIGHT = 30;
const auto BLOCK_WIDTH = 10;

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";
    cout << "<line x1='10' y1='2' x2='" << width + 10 <<"' y2='2' stroke-dasharray = '10 10' stroke='black'/>\n";

}

void svg_end(double top, ostream& stream) {
    stream << "<line x1='10' y1='" << top << "' x2='" << IMAGE_WIDTH <<"' y2='" << top << "' stroke-dasharray = '10 10' stroke='black'/>\n";
    stream << "</svg>\n";
}

void svg_text(double left, double baseline, string text) {
    cout << "<line x1='10' y1='" << baseline -  TEXT_BASELINE << "' x2='10' y2='" << baseline <<"' stroke-dasharray = '10 10' stroke='black'/>\n";
    cout << "<text x='" << left << "' y='" << baseline << "'>" << text <<"</text>\n";
}

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 << "' stroke='" << stroke << "' height='" << height << "' fill='" << fill << "' />\n";
    cout << "<line x1='" << IMAGE_WIDTH <<"' y1='" << y << "' x2='" << IMAGE_WIDTH <<"' y2='" << y + height <<"' stroke-dasharray = '10 10' stroke='black'/>\n";

}



void show_histogram_svg(const vector<size_t>& bins) {
    double max = 0, scale = 1;
    int maxlen = IMAGE_WIDTH - TEXT_WIDTH;
    for (auto el: bins) {
        if (max < el) {
            max = el;
        }
    }
    svg_begin(IMAGE_WIDTH, IMAGE_HEIGHT);
    double top = 5;
    scale = max * BLOCK_WIDTH / maxlen;
    for (size_t bin : bins) {
        const double bin_width = BLOCK_WIDTH * bin;
        svg_text(TEXT_LEFT, top + TEXT_BASELINE, to_string(bin));
        svg_rect(TEXT_WIDTH, top, bin_width / scale, BIN_HEIGHT);
        top += BIN_HEIGHT;
    }
    svg_end(top, cout);
}