#include <iostream>
#include <vector>
#include "histogram.h"
#include "text.h"
#include "svg.h"
#include <curl/curl.h>

using namespace std;

struct Input {
    vector<double> numbers;
    size_t bin_count{};
};

Input input_data(istream& in, bool prompt) {
    if (prompt) {
        cerr << "Enter number count, numbers and bin count: ";
    }

    size_t number_count;
    in >> number_count;

    Input input;
    input.numbers.resize(number_count);

    for (size_t i = 0; i < number_count; i++) {
        in >> input.numbers[i];
    }

    in >> input.bin_count;

    return input;
}

// функция-обработчик для записи полученных данных в stdout
size_t write_data(void* ptr, size_t size, size_t nmemb, void* stream) {
    size_t written = fwrite(ptr, size, nmemb, stdout);
    return written;
}

int main(int argc, char* argv[]) {
    if (argc > 1) {
        CURL* curl = curl_easy_init();
        if (curl) {
            curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);

            // можно настроить User-Agent, если нужно:
            // curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");

            CURLcode res = curl_easy_perform(curl);
            if (res != CURLE_OK) {
                cerr << "cURL error: " << curl_easy_strerror(res) << endl;
            }

            curl_easy_cleanup(curl);
        } else {
            cerr << "curl_easy_init() failed" << endl;
        }
        return 0;
    }

    curl_global_init(CURL_GLOBAL_ALL);
    auto in = input_data(cin, true);
    auto bins = make_histogram(in.numbers, in.bin_count);
    show_histogram_svg(bins);

    return 0;
}
